JAVA
December 16, 2016 | Author: api-3782519 | Category: N/A
Short Description
Download JAVA...
Description
SYLLABUS
Basic concepts of Object Oriented Programming, Genesis of java, History of java, Features of java, Java Virtual Machine (JVM), Difference between java and C++, Java Tokens, Variables and Operators, Array, Conditional Statements, Control Statements. Garbage Collector Classes and Objects, Assess Specifier, Constructor, Subclasses, Inheritance, Abstract Class, Packages and Interfaces, Exception Handling, Applet Programming, AWT package, Layout, Swings, Java Streams, JDBC, Multithreading, Java.Util package
www.arihantinfo.com
Table of Content UNIT 1: Concepts of Object Oriented Programming 1.
Basics of OOP’s 1.1Introduction 1.2Object Oriented Paradigm 1.3Basic concepts of Object Oriented Programming 1.3.1 Object 1.3.2 Classes 1.3.3 Data Abstraction and Encapsulation 1.3.4 Inheritance 1.3.5 Polymorphism
UNIT 2: Fundamentals of Java Language 1. Introduction to Java 2.1 Genesis of Java 2.2 Why Java? 2.3 History of Java 2.4 Oak 2.5 Java Feature 2.5.1 Simple 2.5.2 Secure 2.5.3 Portable 2.5.4 Object Oriented 2.5.5 Interpreted 2.5.6 Robust 2.5.7 Multithreaded 2.5.8 Interpreted 2.5.9 Dynamic and Distributed 2.5.10 Architecture Nature and Portable 2.6 Difference between java and C++ 2.7 The Java Virtual Machine 2.8 Java Program Structure 2.9 Java Token 2.9.1 Identifiers 2.9.2 Keywords 2.9.3 Literals 2.9.4 Operators 2.9.5 Separators 2.10Comments 2.11White Space 2.12Constants 2.13Backslash Character Constant UNIT 3: Variables and Operators 3.1Variables 3.2Data Types in java 3.3Scope of Variables
www.arihantinfo.com
3.4Array 3.4.1 One-Dimensional Array 3.4.2 Two-Dimensional Array 3.5Strings 3.6Operators 3.6.1 Arithmetic Operators 3.6.2 Assignment Operators 3.6.3 Conditional Operators 3.6.4 Special Operators 3.6.5 Relational Operators 3.6.6 Boolean Logical Operators 3.6.7 Incrementing and Decrementing Operators 3.6.8 Bitwise Operators 3.7Operator Precedence UNIT 4: Control Statements 4.1Selection Statements 4.1.1 If 4.1.2 If ..Else 4.1.3 If..Else if .. else 4.2The Switch Statement 4.3Iteration Statement 4.3.1 The while Statement 4.3.2 The do Statement 4.3.3 The for Statement 4.4The Comma Operator 4.5The break Statement 4.6The continue Statement UNIT 5: Classes and Objects 5.1Classes 5.1.1 The class Declaration 5.1.2 Declaring a class’s Superclass 5.1.3 Listing the interface implemented by a class 5.1.4 Summary of a class Declaration 5.2Declaring Member Variables 5.3Declaring Constants 5.4The Method Declaration 5.5Object Creation and Constructors 5.5.1 Object Creation 4.5.2 Constructor 5.6Controlling access to member of a class 5.6.1 Private 5.6.2 Protected 5.6.3 Public 5.7Subclasses and Inheritance 5.7.1 Definition 5.7.2 Creating Subclasses 5.8Overriding Methods 5.9Final classes and Methods 5.9.1 Final Classes
www.arihantinfo.com
5.9.2 Final Methods 5.10 Abstract classes and Methods 5.10.1 Abstract classes 5.10.2 Abstract Methods UNIT 6: Packages and Interfaces 6.1Packages 6.1.1 How to create your own packages 6.2Classpath 6.3The meaning of static 6.4Cleanup: Finalization and Garbage collection 6.5Forcing Finalization and Garbage collection 6.6Interfaces 6.6.1 What is an interface 6.6.2 The interface Declaration 6.6.3 Multiple Extension (Inheritance) 6.6.4 Implementing an interface 6.6.5 Using an interface as a type 6.6.6 Interfaces verses abstract classes UNIT 7: GUI Programming 7.1Introduction to Applet Programming 7.2What are Applets 7.2.1 What applet can do 7.2.2 What applet can not do 7.3Types of an Applet 7.3.1 Local Applet 7.3.1.1 Remote Applet 7.4Lifecycle of an Applet 7.5Passing parameters to an Applet UNIT 8: Programming the Abstract Windowing Toolkit (AWT) 8.1Introduction of AWT 8.2AWT Component Hierarchy 8.3How to Add a Component to a Container 8.4AWT Component 8.4.1 Labels 8.4.2 Buttons 8.4.3 Checkbox 8.4.4 TextFields 8.4.5 TextAreas 8.4.6 Choice lists 8.4.7 Scrolling Lists 8.5Event Handling 8.5.1 Introduction 2.5.2 Event Listener Interfaces 8.6How to implement event handlers: 8.6.1 Buttons 8.6.2 Canvases 8.6.3 Checkboxes
www.arihantinfo.com
8.6.4 8.6.5 8.6.6 8.6.7 8.6.8
Choices Lists ScrollPanes TextComponent Menus
8.7AWT Containers 8.7.1 Frames 8.7.2 Panels 8.7.3 Dialogs 8.8Layouts 8.8.1 8.8.2 8.8.3 8.8.4 8.8.5 8.8.6
The FlowLayout Class The BoderLayout Class The GridLayout Class The GridBagLayout Class The CardLayout class Combining Layouts with Nested Panels
8.9Using Adapters to Handle Events UNIT 9: JFC AND SWING COMPONENT 9.1Introduction 9.2Difference between AWT and Swing Components 9.3Overview of Jcomponent 9.4All about Controls (JComponents) 9.4.1 JApplet Example 9.4.2 JFrame 9.4.3 Changing the Look and Feel (LAF) 9.4.4 Jlabel 9.4.5 JButton 9.4.6 New Feature in JDK 1.2.2 9.4.7 JtoolTip 9.4.8 JtextField 9.4.9 JcheckBox 9.4.10 Jpanel 9.4.11 JSlider Basics UNIT 10: Advance Programming Element Java Streams 10.1What is Stream 10.2Byte Stream 10.2.1 File Stream 10.2.2 Data Stream 10.3 Character Streams 10.3.1 Reading Text Files 10.3.2 Writing Text Files UNIT 11: Exception Handling 11.1Introduction 11.2What are Exception
www.arihantinfo.com
11.3Try/catch 11.4The finally clause 11.5The throws clause 11.6The throw clause 11.7User Define Exception UNIT 12: Java Database Connectivity 12.1 Getting started with JDBC 12.2 What is JDBC 12.3 JDBC Architecture 12.4 JDBC API Interface in a Nutshell 12.4.1 Driver Manager 12.4.2 Connection 12.4.3 Statement 12.4.4 Resultset 12.4.5 CallabelStatement 12.4.6 DatabaseMetaData 12.4.7 Driver 12.4.8 PreparedStatement 12.4.9 ResultSetMetaData 12.4.10DriverPropertyInfo 12.4.11Date 12.4.12Time 12.4.13TimeStamp 12.4.14Types 12.4.15Numeric 12.4.16Driver Interface 12.5 Application Area 12.6 Getting to Work 12.6.1 How to configure ODBC Driver 12.6.2 Connecting to a database 12.6.3 Executing database Queries 12.7 The Statement clause 12.8 The ResultSet class 12.9 More Complex Uses of JDBC 12.9.1 The PreaparedStatement class 12.9.2 The CallableStatement class 12.10Working with Multiple Database 12.11“DNSLess” Connection with the JDBC-ODBC “Bridge” Driver 12.11.1.1 MS Access Example 12.11.1.2 ODBC Driver for Oracle(from Oracle) 12.11.1.3 ODBC Driver for Oracle(from Microsoft) 12.11.1.4 ODBC Driver for Excel UNIT 13: Multithreaded Application 13.1Introduction of Multithreading 13.2What is a Thread 13.3Creating New Threads 13.3.1 Subclassing the Thread class 13.4Implementing the Runnable Interface 13.5Thread States
www.arihantinfo.com
13.6The Thread API 13.7Scheduling and Priority 13.7.1 Setting Thread Priority 13.7.2 Waking up a Thread 13.7.3 Suspending and Resuming Thread Execution 13.7.4 Putting a Thread to Sleep UNIT 14: The Java.util Package 14.1Introduction 14.2The Java collection Advantage: An Overview 14.3A good API 14.4Other Capabilities 14.5Sorting a Collection 14.6Unmodifiable collection 14.7Synchronized Collection
www.arihantinfo.com
UNIT 1: BASICS OF OOP’S
1.1 1.2 1.3
Introduction Object Oriented Paradigm Basic concepts of Object Oriented Programming 1.3.1 Object 1.3.2 Classes 1.3.3 Data Abstraction and Encapsulation 1.3.4 Inheritance 1.3.5 Polymorphism
1.1 Introduction The object-oriented paradigm was first conceived in the 1960's and implemented in languages such as SIMULA-67. One of the initial concerns with early object-oriented languages was their efficiency. Programs written using structured languages, such as Pascal and C, executed faster than programs written using early object-oriented languages. Although programs which used the object-oriented paradigm were more extensible and easier to maintain from a programmer's point of view, an unacceptable price had to be paid in the program's runtime behaviour. Recently, however, the runtime execution of objectoriented programs has improved considerably. This has been due in part to both the development of faster hardware and the creation of efficient languages and compilers which support object-oriented programming, such as C++. These facts, in addition to the everincreasing accessibility of object-oriented languages to the common programmer has created a major evolution in the area of software development. There is, as yet, no universally agreed upon definition of exactly what constitutes objectoriented programming. Booch suggests: “Object-oriented programming is a method of implementation in which programs are organized as cooperative collections of objects, each of which represents an instance of some class, and whose classes are all members of a hierarchy of classes united via inheritance relationships.'' From this definition, one can infer that object-oriented programming consists of instantiating a number of objects which communicate with one another so as to achieve some desired behaviour. This paradigm is natural with how humans see the world; as a series of cause-effect relationships, where an action performed on one object has effects on the objects with which it communicates.
1.2 Object Oriented Paradigm The major objectives of object-oriented approach are to eliminate some of the flaws encountered in the procedural approach. OOP treat data as a critical element in the program development and does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it and protect it from unintentional
www.arihantinfo.com
modification by other functions. OOP allows us to decompose a problem into a number of entities called Object and then build data and function (known as methods in java) around these entities. The combination of data and methods make up an object. The data of an object can be accessed only by the methods associated with that object. However, methods of one object can access the methods of other objects. Some of the features of object-oriented paradigm are: •
Emphasis is on data rather than procedure.
•
Programs are divided into what are known as Objects.
•
Data structures are designed such that they characterized the objects.
•
Methods that operate on the data of an object are tied together in the data structure.
•
Data is hidden and cannot be accessed by external functions.
•
Objects may communication with each other through methods.
•
New data and methods can be easily added whenever necessary.
1.3 Basic concepts of Object Oriented Programming 1.3.1 Object Objects are key to understanding object-oriented technology. You can look around you now and see many examples of real-world objects: your dog, your desk, your television set, your bicycle. These real-world objects share two characteristics: They all have state and behavior. For example, dogs have state (name, color, breed, hungry) and behavior (barking, fetching, and wagging tail). Bicycles have state (current gear, current pedal cadence, two wheels, and number of gears) and behavior (braking, accelerating, slowing down, and changing gears). Software objects are modeled after real-world objects in that they too have state and behavior. A software object maintains its state in one or more variables. A variable is an item of data named by an identifier. A software object implements its behavior with methods. A method is a function (subroutine) associated with an object. Definition: An object is a software bundle of variables and related methods. You can represent real-world objects by using software objects. You might want to represent real-world dogs as software objects in an animation program or a real-world bicycle as software object in the program that controls an electronic exercise bike. You can also use software objects to model abstract concepts. For example, an event is a common object used in GUI window systems to represent the action of a user pressing a mouse button or a key on the keyboard. The following illustration is a common visual representation of a software object:
www.arihantinfo.com
Everything that the software object knows (state) and can do (behavior) is expressed by the variables and the methods within that object. A software object that modeled your realworld bicycle would have variables that indicated the bicycle's current state: its speed is 10 mph, its pedal cadence is 90 rpm, and its current gear is the 5th gear. These variables are formally known as instance variables because they contain the state for a particular bicycle object, and in object-oriented terminology, a particular object is called an instance. The following figure illustrates a bicycle modeled as a software object.
In addition to its variables, the software bicycle would also have methods to brake, change the pedal cadence, and change gears. (The bike would not have a method for changing the speed of the bicycle, as the bike's speed is just a side effect of what gear it's in, how fast the rider is pedaling, whether the brakes are on, and how steep the hill is.) These methods are formally known as instance methods because they inspect or change the state of a particular bicycle instance.
1.3.2 Classes In the real world, you often have many objects of the same kind. For example, your bicycle is just one of many bicycles in the world. Using object-oriented terminology, we say that your bicycle object is an instance of the class of objects known as bicycles. Bicycles have some state (current gear, current cadence, two wheels) and behavior (change gears, brake) in common. However, each bicycle's state is independent of and can be different from that of other bicycles. When building bicycles, manufacturers take advantage of the fact that bicycles share characteristics, building many bicycles from the same blueprint. It would be very inefficient to produce a new blueprint for every individual bicycle manufactured. In object-oriented software, it's also possible to have many objects of the same kind that share characteristics: rectangles, employee records, video clips, and so on. Like the bicycle manufacturers, you can take advantage of the fact that objects of the same kind are similar and you can create a blueprint for those objects. A software blueprint for objects is called a class.
www.arihantinfo.com
Definition: A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind.
The class for our bicycle example would declare the instance variables necessary to contain the current gear, the current cadence, and so on, for each bicycle object. The class would also declare and provide implementations for the instance methods that allow the rider to change gears, brake, and change the pedaling cadence, as shown in the next figure.
After you've created the bicycle class, you can create any number of bicycle objects from the class. When you create an instance of a class, the system allocates enough memory for the object and all its instance variables. Each instance gets its own copy of all the instance variables defined in the class.
In addition to instance variables, classes can define class variables. A class variable contains information that is shared by all instances of the class. For example, suppose that all bicycles had the same number of gears. In this case, defining an instance variable to hold the number of gears is inefficient; each instance would have its own copy of the variable, but the value would be the same for every instance. In such situations, you can define a class variable that contains the number of gears. All instances share this variable. If one object changes the variable, it changes for all other objects of that type. A class can also declare class methods. You can invoke a class method directly from the class, whereas you must invoke instance methods on a particular instance.
www.arihantinfo.com
1.3.3 Data Abstraction and Encapsulation The wrapping up of data and methods into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world and only those methods, which are wrapped in the class, can access it. These methods provide the interface between the object’s data and program. The insulation of data from direct access by the program is called data hiding. Encapsulation makes it possible for objects to be treated like ‘black boxes’, each performing a specific task without any concern for internal implementation. Information “in” Data and Method
Information “out”
Encapsulation is like a capsule: the doctor tells you to take a medicinal capsule or pill. Far too small for you to see is the structure of the compound or molecule that does work in your bloodstream or organs to cure your disease. You don't even see the components of the mixture, which might be white medicine mixed with, say green flour. The complexity is hidden from you. Your orders are simple and external to the encapsulation: take one green pill each day with water. Encapsulation is like a black box. When you purchase a television set, you do not need to know the details of the electronics inside (raster-scanning cathode ray tube with magnetic electron gun, alternating current transformer, hundreds of capacitors, thousands of transistors). Instead, you only need to know how to plug in the UNIT, attach the cable, turn the on switch, and press buttons on the remote control. You have a UNIT that sends visual and audio messages to you, and you do not care about the hidden actions within the unit.
Abstraction Refers to the act of representing essential features without including the background details or explanations.
1.3.4 Inheritance
www.arihantinfo.com
Generally speaking, objects are defined in terms of classes. You know a lot about an object by knowing its class. Even if you don't know what a penny-farthing is, if I told you it was a bicycle, you would know that it had two wheels, handle bars, and pedals. Object-oriented systems take this a step further and allow classes to be defined in terms of other classes. For example, mountain bikes, racing bikes, and tandems are all kinds of bicycles. In object-oriented terminology, mountain bikes, racing bikes, and tandems are all subclasses of the bicycle class. Similarly, the bicycle class is the superclass of mountain bikes, racing bikes, and tandems. This relationship is shown in the following figure.
Each subclass inherits state (in the form of variable declarations) from the superclass. Mountain bikes, racing bikes, and tandems share some states: cadence, speed, and the like. Also, each subclass inherits methods from the superclass. Mountain bikes, racing bikes, and tandems share some behaviors: braking and changing pedaling speed, for example. However, subclasses are not limited to the state and behaviors provided to them by their superclass. Subclasses can add variables and methods to the ones they inherit from the superclass. Tandem bicycles have two seats and two sets of handle bars; some mountain bikes have an extra set of gears with a lower gear ratio. Subclasses can also override inherited methods and provide specialized implementations for those methods. For example, if you had a mountain bike with an extra set of gears, you would override the "change gears" method so that the rider could use those new gears. You are not limited to just one layer of inheritance. The inheritance tree, or class hierarchy, can be as deep as needed. Methods and variables are inherited down through the levels. In general, the farther down in the hierarchy a class appears, the more specialized its behavior. The Object class is at the top of class hierarchy, and each class is its descendant (directly or indirectly). A variable of type Object can hold a reference to any object, such as an instance of a class or an array. Object provides behaviors that are required of all objects running in the Java Virtual Machine. For example, all classes inherit Object's toString method, which returns a string representation of the object. Inheritance offers the following benefits: •
Subclasses provide specialized behaviors from the basis of common elements provided by the superclass. Through the use of inheritance, programmers can reuse the code in the superclass many times.
•
Programmers can implement superclasses called abstract classes that define "generic" behaviors. The abstract superclass defines and may partially implement the behavior, but much of the class is undefined and unimplemented. Other programmers fill in the details with specialized subclasses.
www.arihantinfo.com
1.3.5 Polymorphism Polymorphism is the combination of the two Greek world, poly i.e. many and morphism i.e. forms, means the ability to take more than one form. For example, an operation may exhibit different behavior in different instance. The behavior depends upon the types of data used in the operation. For example, consider the operation of addition. For two numbers, the operation will generate a sum. If the operands are string, then the operation would produce a third string by concatenation.
www.arihantinfo.com
UNIT 2 : INTRODUCTION TO JAVA
Introduction to Java 2.1Genesis of Java 2.2Why Java? 2.3History of Java 2.4Oak 2.5Java Feature 2.5.1 Simple 2.5.2 Secure 2.5.3 Portable 2.5.4 Object Oriented 2.5.5 Interpreted 2.5.6 Robust 2.5.7 Multithreaded 2.5.8 Interpreted 2.5.9 Dynamic and Distributed 2.5.10 Architecture Nature and Portable 2.6Difference between java and C++ 2.7The Java Virtual Machine 2.8Java Program Structure 2.9Java Token 2.9.1 Identifiers 2.9.2 Keywords 2.9.3 Literals 2.9.4 Operators 2.9.5 Separators 2.10Comments 2.11White Space 2.12Constants 2.13Backslash Character Constant
2.1 Genesis of Java Java is related to C++, which is a direct descendent of C. Much of the character of Java is inherited from these two languages. From C, Java derives its syntax. Many of Java's object oriented features were influenced by C++. By the end of the 1980's and early 1990's object oriented programming using C++ took hold. It seemed that programmers had finally found the perfect language but there were forces brewing that would drive the computer language evolution forward. These forces were the World Wide Web and the Internet. As stated earlier in these notes, in 1990 a group at SUN Microsystems developed Java. In some sense Java is what C++ might have been if it was not required to be backward compatible with C. Java was originally called Oak but that turned out to be a copyrighted name so after some brainstorming they chose the name Java. It doesn't really mean Just another Vague Acronym.
www.arihantinfo.com
The original motivation of Java was not the Internet but was the need for a platform independent language. This platform independence is exactly what is needed for Internet programming. The Internet helped push Java to the forefront of programming and Java in turn has a profound effect on the Internet. Java has gone through two major upgrades from the original version 1.0.2 to version 1.1 and now to version 1.2 (also called Java 2). There are major changes in the language between the versions.
2.2 Why Java? In one of their early papers about the language, Sun described Java as follows: Java: a simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, and dynamic language. Even though this is quite a string of buzzwords, they aptly describe the language.
2.3 History of Java At first glance, it may appear that Java was developed specifically for the World Wide Web. However, interestingly enough, Java was developed independently of the web, and went through several stages of metamorphosis before reaching its current status of de facto programming language for the World Wide Web. Below is a brief history of Java since its infancy to its current state.
2.4 Oak Bill Joy, currently a vice president at Sun Microsystems, is widely believed to have been the person to conceive of the idea of a programming language that later became Java. In late 1970's, Joy wanted to design a language that combined the best features of MESA and C. In an attempt to re-write the UNIX operating system in 1980's, Joy decided that C++ was inadequate for the job. A better tool was needed to write short and effective programs. It was this desire to invent a better programming tool that swayed Joy, in 1991, in the direction of Sun's "Stealth Project" - as named by Scott McNealy, Sun's president. In January of 1991, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton (formerly the project leader of Sun's OpenWindows user environment), and several other individuals met in Aspen, Colorado for the first time to discuss the ideas for the Stealth Project. The goal of the Stealth Project was to do research in the area of application of computers in the consumer electronics market. The vision of the project was to develop "smart" consumer electronic devices that could all be centrally controlled and programmed from a handheldremote-control-like device. According to Gosling, "the goal was ... to build a system that would let us do a large, distributed, heterogeneous network of consumer electronic devices all talking to each other." With this goal in mind, the stealth group began work.
www.arihantinfo.com
Members of the Stealth Project, which later became known as the Green Project, divided the tasks amongst themselves. Mike Sheradin was to focus on business development, Patrick Naughton was to begin work on the graphics system, and James Gosling was to identify the proper programming language for the project. Gosling, who had joined Sun in 1984, had previously developed the commercially unsuccessful NEWS windowing system as well as GOSMACS - a C language implementation of GNU EMACS. He began with C++, but soon after was convinced that C++ was inadequate for this particular project. His extensions and modifications to C++ (also know as C++ ++ --), were the first steps towards the development of an independent language that would fit the project objectives. He named the language "Oak" while staring at an oak tree outside his office window! The name "Oak" was later dismissed due to a patent search which determined that the name was copyrighted and used for another programming language. According to Gosling, "the Java development team discovered that Oak was the name of a programming language that predated Sun's language, so another name had to be chosen." "It's surprisingly difficult to find a good name for a programming language, as the team discovered after many hours of brainstorming. Finally, inspiration struck one day during a trip to the local coffee shop" Gosling recalls. Others have speculated that the name Java came from several individuals involved in the project: James gosling, Arthur Van hoff, Andy bechtolsheim. There were several criteria that Oak had to meet in order to satisfy the project objective given the consumer electronics target market. Given the wide array of manufacturers in the market, Oak would have to be completely platform independent, and function seamlessly regardless of the type of CPU in the device. For this reason, Oak was designed to be an interpreted language, since it would be practically impossible for a complied version to run on all available platforms. To facilitate the job of the interpreter, Oak was to be converted to an intermediate "byte-code" format, which is then passed around across the network, and executed/interpreted dynamically. Additionally, reliability was of great concern. A consumer electronics device that would have to be "rebooted" periodically was not acceptable. Another important design objective for Oak would then have to be high reliability by allowing the least amount of programmerintroduced errors. This was the motivation for several important modifications to C++. The concepts of multiple-inheritance and operator overloading were identified as sources of potential errors, and eliminated in Oak. Furthermore, in contrast to C++, Oak included implicit garbage collection thereby providing efficient memory utilization and higher reliability. Finally, Oak attempted to eliminate all unsafe constructs used in C and C++ by only providing data structures within objects. Another essential design criterion was security. By design, Oak-based devices were to function in a network and often exchange code and information. Inherently, security is of great concern in a networked environment, especially in an environment as network dependent as the conceived Oak-based systems. For this reason, pointers were excluded in the design of Oak. This would theoretically eliminate the possibility of malicious programs accessing arbitrary addresses in memory. 2.5 Java Feature • • •
Simple Secure Portable
www.arihantinfo.com
• • • • • •
Object Oriented Robust Multithreaded Interpreted Distributed Architecture Neutral and Portable
2.5.1 Simple Java was designed to be easy for the professional programmer. It is easy to learn and can be used effectively. If you are an experienced C++ programmer, moving to Java will require very little effort. Does not use pointers. Since Java does not have structures, and strings and arrays are objects, there's no need for pointers. Does not use goto -- instead, provide labeled Break and Continue statements, and exception handling. Unlike C++, Java has no operator overloading, no multiple inheritance. 2.5.2 Secure There is a concept of applets in Java, which can be downloaded without fear or virus or malicious content, because the Java programs are confined to Java execution environment and are not allowed to access other parts of the CPU. Java programs cannot forge pointers to memory, or overflow arrays, or read memory outside of the bounds of an array or string. Byte-code verification process, performed by interpreter on any untrusted code that it loads -- checks for stack overflows and underflows, illegal byte-codes, etc.
2.5.3 Portable The Java programs called Applets run in the JVM (Java virtual machine) environment that is in every browser therefore the programs can run anywhere. 2.5.4 Object Oriented Class: collection of data and methods that operate on that data Java comes with an extensive set of classes, arranged in packages. Most things in Java are objects. The only exceptions: the primitive number, character, and boolean types. Strings are represented by objects, as are threads.
www.arihantinfo.com
A class is the basic unit of compilation and of execution in Java; all Java programs are classes.
2.5.5 Interpreted The Java compiler generates byte-codes for the Java Virtual Machine (JVM), rather than native machine code.
2.5.6 Robust Garbage collection and Exception handling make Java a robust language. In garbage collection the user doesn’t have to bother about the memory allocation as, when the object is no longer in use it is automatically deleted to release memory space. 2.5.7 Multithreaded A single threaded application has one thread of execution running at all times and such programs can do only one task at a time. A multi-threaded application can have several threads of execution running independently and simultaneously. These threads may communicate and cooperate and will appear to be a single program to the user. 2.5.8 Interpreted The Java code is compiled into the byte code, which is the class file. The byte code is then interpreted to the machine language by the JVM environment. 2.5.9 Dynamic and Distributed Any class can be loaded into a running Java interpreter at any time, then dynamically instantiated. Native code libraries can also be dynamically loaded. Classes in Java are represented by the Class class. Information about a class is available dynamically at run-time. See Reflection.... "Distributed" means lots of high-level support for networking (e.g. URL class in java.net package). Distributed nature of Java, combined with dynamic class loading capabilities, make it possible for a Java interpreter to download and run code across the Internet.
1.5.10 Architecture Neutral and Portable "Write once, run anywhere" JVM = interpreter and run-time system, ported to various platforms
www.arihantinfo.com
No implementation-dependent aspects -- e.g. all primitive data types are defined in Java, have same byte size on all platforms. 2.6 Differences between Java and C++ •
Perhaps the single biggest difference between Java and C++ is that Java does not support pointers. After examining C++ in detail we know that the pointer is one of C++'s most powerful and important language features. It is also one of the most dangerous. Pointers don't exist in Java, as their existence would violate security aspects of the language. For example, using a pointer to gain access to memory addresses outside a program's code and data a malicious program could damage the system, perform unauthorized access etc.
•
In Java all object variables, arguments and return types are references. There is no need for the reference operator, &, of C++.
•
In Java, assigning one object to another does not invoke an assignment operator function. Instead, assigning one object to another has the effect of associating the variable with another location in memory, much like a pointer assignment.
•
Java has a streamlined approach to memory allocation. Like C++, it supports the new keyword (which returns a reference). However it does not have a delete. Instead, when the last reference to an object is destroyed (goes out of scope), the object itself is destroyed the next time garbage collection occurs. The garbage collector runs as a background process freeing up unused memory.
•
Java does not support operator overloading. This is not such a big restriction as we might think. After all, it is just as easy to say u = v.add (w) as u = v + w. This is precisely the notation used when we make the matrix class within Java.
•
Java does not support complex numbers and since it does not support operator overloading we can't build complex numbers ourselves as is done in C++.
•
Java does not include a preprocessor nor does it support preprocessor directives. The preprocessor plays a lesser role in C++ than in C and the designers of Java felt that it was time to eliminate it entirely.
•
Java does not support automatic type conversions that result in a loss of precision.
•
All the code in a Java program is encapsulated within one or more classes. Therefore Java does not have what you would normally think of as global variables or functions.
•
Java does not allow default arguments.
•
Java does not support multiple inheritance. Java does support the interface, which is similar to abstract classes in C++, and does give a form of multiple inheritance.
•
Java does not support templates. In Java all classes inherit from a single class called Object so that it is not difficult to write generalized classes building on the Object class as the base type.
www.arihantinfo.com
2.7 The Java Virtual Machine MACHINE LANGUAGE CONSISTS of very simple instructions that can be executed directly by the CPU of a computer. Almost all programs, though, are written in high-level programming languages such as Java, Pascal, or C++. A program written in a high-level language cannot be run directly on any computer. First, it has to be translated into machine language. This translation can be done by a program called a compiler. A compiler takes a high-level-language program and translates it into an executable machine-language program. Once the translation is done, the machine-language program can be run any number of times, but of course it can only be run on one type of computer (since each type of computer has its own individual machine language). If the program is to run on another type of computer it has to be re-translated, using a different compiler, into the appropriate machine language. There is an alternative to compiling a high-level language program. Instead of using a compiler, which translates the program all at once, you can use an interpreter, which translates it instruction-by-instruction, as necessary. An interpreter is a program that acts much like a CPU, with a kind of fetch-and-execute cycle. In order to execute a program, the interpreter runs in a loop in which it repeatedly reads one instruction from the program, decides what is necessary to carry out that instruction, and then performs the appropriate machine-language commands to do so. One use of interpreters is to execute high-level language programs. For example, the programming language Lisp is usually executed by an interpreter rather than a compiler. However, interpreters have another purpose: they can let you use a machine-language program meant for one type of computer on a completely different type of computer. For example, there is a program called "Virtual PC" that runs on Macintosh computers. Virtual PC is an interpreter that executes machine-language programs written for IBM-PC-clone computers. If you run Virtual PC on your Macintosh, you can run any PC program, including programs written for Windows. (Unfortunately, a PC program will run much more slowly than it would on an actual IBM clone. The problem is that Virtual PC executes several Macintosh machine-language instructions for each PC machine-language instruction in the program it is interpreting. Compiled programs are inherently faster than interpreted programs.) The designers of Java chose to use a combination of compilation and interpretation. Programs written in Java are compiled into machine language, but it is a machine language for a computer that doesn't really exist. This so-called "virtual" computer is known as the Java virtual machine. The machine language for the Java virtual machine is called Java bytecode. There is no reason why Java bytecode could not be used as the machine language of a real computer, rather than a virtual computer. In fact, Sun Microsystems -- the originators of Java -- have developed CPU's that run Java bytecode as their machine language. However, one of the main selling points of Java is that it can actually be used on any computer. All that the computer needs is an interpreter for Java bytecode. Such an interpreter simulates the Java virtual machine in the same way that Virtual PC simulates a PC computer. Of course, a different Java bytecode interpreter is needed for each type of computer, but once a computer has a Java bytecode interpreter, it can run any Java bytecode program. And the same Java bytecode program can be run on any computer that has such an
www.arihantinfo.com
interpreter. This is one of the essential features of Java: the same compiled program can be run on many different types of computers.
Why, you might wonder, use the intermediate Java bytecode at all? Why not just distribute the original Java program and let each person compile it into the machine language of whatever computer they want to run it on? There are many reasons. First of all, a compiler has to understand Java, a complex high-level language. The compiler is itself a complex program. A Java bytecode interpreter, on the other hand, is a fairly small, simple program. This makes it easy to write a bytecode interpreter for a new type of computer; once that is done, that computer can run any compiled Java program. It would be much harder to write a Java compiler for the same computer. Furthermore, many Java programs are meant to be downloaded over a network. This leads to obvious security concerns: you don't want to download and run a program that will damage your computer or your files. The bytecode interpreter acts as a buffer between you and the program you download. You are really running the interpreter, which runs the downloaded program indirectly. The interpreter can protect you from potentially dangerous actions on the part of that program. 2.8 Java Program Structure public class ClassName {
www.arihantinfo.com
class body public static void main (String[] args) { method body } } public class Hello { public static void main(String[] args) { System.out.println("Hello"); } } Save this program in the folder say C:\javaprogram. The name of the class is the same as the name of the file. When you’re creating a stand-alone program such as this one, one of the classes in the file must have the same name as the file. (The compiler complains if you don’t do this.) That class must contain a method called main () with the signature shown: public static void main(String[] args) The public keyword means that the method is available to the outside world. The static keyword means that no need to create an object of this class to access the main function. The void means function is not returning anything. The main keyword is the name of the main function from where the execution will start and args are the command line arguments. By default java import a package java.lang and in this package we have a System class, and System class has a static object out of PrintStream class. Since it’s static you don’t need to create anything. The out object is always there and provides a println( ) function, which is used to print the string on the console and end with a new line.” Thus, in any Java program you write you can say System.out.println("things") whenever you want to print something to the console. Compiling and running In order to compile the program open the command prompt and go to your directory and write this command. C:\javaprogram>javac Hello.java This command should produce no response. But it will create Hello.class file in your folder which is the bytecode of this program. In order to run this program, write this command on the same command prompt. C:\javaprogram>java Hello Output will be: Hello
www.arihantinfo.com
2.9 Java Token: A java program is a collection of tokens, comments and white spaces. Java language includes five types of tokens. They are: • • • • •
Identifier Keyword Literal Separator Operator
2.9.1 Identifiers The Java identifiers are the names given for classes, methods, variables, objects, labels, packages and interfaces in a program. Here are the rules for creating a properly formed identifier: 1. are names for classes, methods, or variables. 2. begin with a letter, underscore (_), or dollar sign ($). Java Identifiers
3. are case sensitive. 4. have no maximum length. 5. must not begin with digit.
Identifiers must be meaningful, short enough to be quickly and easily typed and long enough to be descriptive and easily read.
2.9.2 Keywords The following character sequences are reserved for use as keywords and cannot be used as identifiers Keyword: one of abstract do import return try char float new
default implements public transient catch finally native switch
if
private this boolean protected throw break double throws byte else instanceof case extends int short final interface static void long strictfp volatile class super while const for continue goto package synchronized
The keywords const and goto are reserved, even though they are not currently used. This may allow a Java compiler to produce better error messages if these C++ keywords incorrectly appear in programs.
2.9.3 Literals
www.arihantinfo.com
Literal in java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables. Java language specifies five major types of literals. They are: Integer Literal Floating-Point Literal Boolean Literal Character Literal String Literal Null Literal
2.9.4 Operators An operator is a symbol that takes one or more arguments and operates on them to produce a result. The following 37 tokens are the operators, formed from ASCII characters: Operator: = == + > ^=
< >= * >>> %=
! != / += =
? || | *= >>>=
: ++ ^ /=
-% &=
2.9.5 Separators Separators are symbols used to indicate where groups of code are divided and arranged. They basically define the shape and function of our code. The following ASCII characters are the separators (punctuators): Separator: one of () { }Braces [] ; , .
Parentheses Brackets Semicolon Comma Period
2.10 Comments There are two kinds of comments /* text */ A traditional comment: all the text from the ASCII characters /* to the ASCII characters */ is ignored (as in C and C++). // text A end-of-line comment: all the text from the ASCII characters // to the end of the line is ignored (as in C++). 2.11 White Space White space is defined as the ASCII space, horizontal tab, and form feed characters, as well as line terminators WhiteSpace:
www.arihantinfo.com
the ASCII SP character, also known as "space" the ASCII HT character, also known as "horizontal tab" the ASCII FF character, also known as "form feed" LineTerminator 2.12
Constants
•
A constant is an identifier that is similar to a variable except that it holds one value for its entire existence
•
The compiler will issue an error if you try to change a constant
•
In Java, we use the final modifier to declare a constant final int count = 100;
2.13
Backslash Character Constants Constants • • • • • • • •
‘\b’ ‘\f’ ‘\n’ ‘\r’ ‘\t’ ‘\’’ ‘\”’ ‘\\’
Meanings back space form feed new line carriage return horizontal tab single quote double quote backslash
www.arihantinfo.com
UNIT 3: VARIABLES AND OPERATORS
3.1Variables 3.2Data Types in java 3.3Scope of Variables 3.4Array 3.4.1 One-Dimensional Array 3.4.2 Two-Dimensional Array 3.5Strings 3.6Operators 3.6.1 Arithmetic Operators 3.6.2 Assignment Operators 3.6.3 Conditional Operators 3.6.4 Special Operators 3.6.5 Relational Operators 3.6.6 Boolean Logical Operators 3.6.7 Incrementing and Decrementing Operators 3.6.8 Bitwise Operators 3.6.9 Operator Precedence
3.1 Variables A variable is an identifier that denotes a storage location used to store a data value. A variable name can be chosen by the programmer in a meaningful way so as to reflect what it represents in the program. Variable name may consist of alphabets, digits, the underscore ( _ ) and dollar character, subject to the following conditions: 1. They must not begin with a digit. 2. Uppercase and lowercase are distinct. This means that the variable Amount is not equal to amount or AMOUNT. 3. It should not be a keyword. 4. White space is not allowed. 5. Variable name can be of any length.
www.arihantinfo.com
Data Types Non-primitive
Primitive
Numeric
Integer
Non-numeric
Floating-point Character
char
byte
short
classes
Interface
Arrays
Boolean
boolean
float
int double long
Every variable must have a data type. A variable's data type determines the values that the variable can contain, size it takes in memory and the operations that can be performed on it. 2.2 Data type in Java The Java programming language has two categories of data types: 1. 2.
Primitive Reference
A variable of primitive type contains a single value of the appropriate size and format for its type: A Number, A Character, or A boolean value. The following table lists, by keyword, all of the primitive data types supported by Java, their sizes and a brief description of each.
Primitive Data Types
Keyword
Description
Size
(integers)
www.arihantinfo.com
Byte
Byte-length integer
One byte
Short
Short integer
Two bytes
Int
Integer
Four bytes
Long
Long integer
Eight bytes
Float
Single-precision floating point
Four bytes
Double
Double-precision floating point
Eight bytes
Char
A single character
Two bytes (Unicode character)
Boolean
A Boolean value (true or false)
true or false
(real numbers)
(other types)
Purity Tip: In other languages, the format and size of primitive data types may depend on the platform on which a program is running. In contrast, the Java programming language specifies the size and format of its primitive data types. Hence, you don't have to worry about system-dependencies. You can put a literal primitive value directly in your code. For example, if you need to assign the value 4 to an integer variable you can write this: int anInt = 4; The digit 4 is a literal integer value. Here are some examples of literal values of various primitive types: Examples of Literal Values and Their Data Types
Literal 178 8864L 37.266 37.266D 87.363F 26.77e3 'c' True False
Data Type Int Long Double Double Float Double Char Boolean Boolean
Generally speaking, a series of digits with no decimal point is typed as an integer. You can specify a long integer by putting an 'L' or 'l' after the number. 'L' is preferred, as it cannot be confused with the digit '1'. A series of digits with a decimal point is of type double. You can specify a float by putting an 'f' or 'F' after the number. A literal character value is any single
www.arihantinfo.com
Unicode character between single quote marks. The two boolean literals are simply true and false. Arrays, classes, and interfaces are reference types. The value of a reference type variable, in contrast to that of a primitive type, is a reference to (an address of) the value or set of values represented by the variable. A reference is called a pointer or a memory address in other languages. The Java programming language does not support the explicit use of addresses like other languages do. You use the variable's name instead.
3.3 Scope of Variables A variable's scope is the region of a program within which the variable can be referred to by its simple name. Secondarily, scope also determines when the system creates and destroys memory for the variable. Scope is distinct from visibility, which applies only to member variables and determines whether the variable can be used from outside of the class within which it is declared. Visibility is set with an access modifier. The location of the variable declaration within your program establishes its scope and places it into one of these categories: •
Instance variables
•
Class variables
•
Local variable
Instance and class variables are declared inside a class. Instance variable are created when the objects are instantiated and therefore they are associated with the objects. They take different values for each object. On the other hand, class variables are global to a class and belong to the entire set of objects that class creates. Only one memory location is created for each class variable. Variables declared and used inside methods are called local variables. They are called so because they are not available for use outside the method definition. Local variables can also be declared inside program blocks that are defined between an opening brace { and a closing brace }.These variables are visible to the program only from the beginning of its program block to the end of the program block. When the program control leaves a block, all the variables in the block will cease to exist. The are of the program where the variable is accessible (i.e. usable) is called its scope.
3.4 Array An array is a group of contiguous or related data items that share a common name. Or we can say that an array stores multiple variables of •
the same type.
www.arihantinfo.com
•
a specific number of indices ("slots").
•
you access an element by using its index.
3.4.1 One-Dimensional Arrays A list of items can be given one variable name using only one subscript and such a variable is called a single-subscript variable or a one-dimensional array. Declaration of Arrays: type arrayname [] = new type[size]; For example we want to represent a set of five numbers, say (35, 40, 20, 57, 19) by an array variable number, then we may create the variable number as follows int number[]=new int[5]; and computer reserves five storage locations as shown below 35
40
number[0]
number[1]
20
57 number[2]
19 number[3]
number[4]
Note that java creates arrays starting with a subscript of 0 and ends with a value one less than the size specified. Unlike C, Java protects arrays from overruns and underruns. Trying to access an array beyond its boundaries will generate an error message. Initialization of Arrays: arrayname[subscript]=value; we can also initialize array automatically in the same way as the ordinary variables when they are declared, as shown below. type arrayname[ ] = {list of values}; Example : int number [ ] = {35, 40, 20, 57, 19}; Array Length In java, all arrays store the allocated size in a variable named length. We can access the length of the array a using a.length. Example: int aSize = a.length;
3.4.2 Two-Dimensional Arrays
www.arihantinfo.com
So far we have discussed the array variables that can store a list of values. There will be situations where a table of values will have to be stored. Consider the following data table, which shows the value of sales of three items by four salesgirls:
Salesgirl Salesgirl Salesgirl Salesgirl
#1 #2 #3 #4
Item1
Item2
Item3
310 210 405 260
275 190 235 300
365 325 240 380
The table contains a total of 12 values, there in each line. We can think of this table as a matrix consisting of four rows and three columns. Each row represents the values of sales by a particular salesgirl and each column represents the values of sales of a particular item. For creating two-dimensional arrays, we must follow the same steps as that of simple arrays, we may create a two-dimensional array like this: type arrayname[][]=new type[row][col]; int myarray = new int[3][4]; like the one-dimensional array, two-dimensional array may be initialized by following their declaration with a list of initial values enclosed in braces. For example, int table[2][3] = {2, 2, 2, 4, 4, 4}; initialize the elements of the first row to zero and the second row to one. The initialization is done row by row. The above statement can be equivalently written as int table[ ] [ ] = { {2, 2, 2}, {4, 4, 4}}; by surrounding the elements of each row by braces.
3.5 Strings Internally, a String is an array of characters, an array of char. The Java API, however, considers a String to be an object. Therefore, you benefit from built-in methods and property to help you handle strings.
3.6 Operators 3.6.1 Arithmetic Operators Operator
Name
Use
Description
+
Addition
Op1 + op2
Adds op1 and op2
-
Subtraction
Op1 - op2
Subtracts op2 from op1
www.arihantinfo.com
*
multiplication
Op1 * op2
Multiplies op1 by op2
/
Division
Op1 / op2
Divides op1 by op2
%
modulus (or mod) Op1 % op2 Computes the remainder of dividing op1 by op2
The arithmetic operators return a number. numeric return value = ; example: myLongString = myShortString + myOtherString; •
•
+ addition o
adds two numbers
o
concatenates two string objects
- subtraction o
•
* multiplication o
•
multiply two numbers
/ division o
•
subtract one number from another
divide two numbers
% modulus o
the remainder of an integer division
o
5 % 3 = 2 Because 5/3 = 1 and leaves 2.
o
myRemainder = 5 % 3;
3.6.2 Assignment Operator You use the assignment operator, =, to assign one value to another. Compound Assignment Operator
Operator
Use
Equivalent to
+=
Op1 += op2
Op1 = op1 + op2
-=
Op1 -= op2
Op1 = op1 - op2
*=
Op1 *= op2
Op1 = op1 * op2
/=
Op1 /= op2
Op1 = op1 / op2
%=
Op1 %= op2
Op1 = op1 % op2
www.arihantinfo.com
&=
Op1 &= op2
Op1 = op1 & op2
|=
Op1 |= op2
Op1 = op1 | op2
^=
Op1 ^= op2
Op1 = op1 ^ op2
> op2
>>>=
Op1 >>>= op2
Op1 = op1 >>> op2
3.6.3 Conditional Operator Operator
Use
Description
?:
Exp1 ? exp2 : exp3
If op1 is true, returns op2. Otherwise, returns op3. (This is the conditional operator.)
3.6.4 Special Operators
[]
Type []
Declares an array of unknown length, which contains type elements.
[]
Type[ op1 ]
Creates and array with op1 elements. Must be used with the new operator.
[]
op1[ op2 ]
Accesses the element at op2 index within the array op1. Indices begin at 0 and extend through the length of the array minus one.
.
op1.op2
Is a reference to the op2 member of op1.
()
op1(params )
Declares or calls the method named op1 with the specified parameters. The list of parameters can be an empty list. The list is comma-separated.
(type)
(type) op1
Casts (converts) op1 to type. An exception will be thrown if the type of op1 is incompatible with type.
new
New op1
Creates a new object or array. op1 is either a call to a constructor, or an array specification.
Instanceof
op1 instanceof Returns true if op1 is an instance of op2 op2
3.6.5 Relational Operators Logical operators test a condition by comparing values and return a boolean value (true or false). •
== equal (two adjacent equal signs) if (sum = = 100) { // do something ...
www.arihantinfo.com
WARNING: Testing for identical values with = = is different from assigning a value with = •
!= not equal if (sum != 100) { // do something ...
•
> greater than if (sum > 100) { // do something ...
•
< less than if (sum < 100) { // do something ...
•
>= greater than or equal to if (sum >= 100) { // do something ...
•
y ) { // nested 'if' // do this // Note: any number of "else if" clauses after "if" and before "else" } else { // do this } Note: The "else" is for the last statement.
The output is: x not > or = to y 4.2 The switch Statement •
The switch statement provides another means to decide which statement to execute next
•
The switch statement evaluates an expression, then attempts to match the result to one of several possible cases
•
Each case contains a value and a list of statements
www.arihantinfo.com
•
The flow of control transfers to statement list associated with the first value that matches
The general syntax of a switch statement is: switch ( expression ) { case value1 : statement-list1; break; case value2 : statement-list2; break; case value3 : statement-list3; break; default : statement-list4; break; } •
Often a break statement is used as the last statement in each case's statement list
•
A break statement causes control to transfer to the end of the switch statement
•
If a break statement is not used, the flow of control will continue into the next case
•
A switch statement can have an optional default case
• •
If the default case is present, control will transfer to it if no other case value matches The test variable or expression to be tested can be of the primitive types byte, char, short, or int
Example : For example, the program: class Toomany { static void howMany(int k) { switch (k) { case 1: System.out.print("one "); case 2: System.out.print("too "); case 3: System.out.println("many"); } } public static void main(String[] args) { howMany(3); howMany(2); howMany(1); } } contains a switch block in which the code for each case falls through into the code for the next case. As a result, the program prints: many too many
www.arihantinfo.com
one too many If code is not to fall through case to case in this manner, then break statements should be used, as in this example: class Twomany { static void howMany(int k) { switch (k) { case 1: System.out.println("one"); break; // exit the switch case 2: System.out.println("two"); break; // exit the switch case 3: System.out.println("many"); break; // not needed, but good style } } public static void main(String[] args) { howMany(1); howMany(2); howMany(3); } } This program prints: one two many 4.3 Iteration Statements Java has three kinds of repetition statements: the while loop, the do loop, and the for loop
4.3.1 The while Statement The while statement executes an Expression and a Statement repeatedly until the value of the Expression is false. While Statement: while (Expression) Statement The Expression must have type boolean, or a compile-time error occurs. The while is an entry-controlled loop statement. Therefore, the body of a while loop will execute zero or more times public class WhileTest { public static void main(String[] args) { int r = 0; while(r < 3) { System.out.println(r); } } }
www.arihantinfo.com
The output will be 0 1 2
4.3.2 The do Statement The do statement executes a Statement and an Expression repeatedly until the value of the Expression is false. do { statement; } while ( condition ) The statement is executed once initially, and then the condition is evaluated The statement is repetitively executed until the condition becomes false •
A do loop is similar to a while loop, except that the condition is evaluated after the body of the loop is executed
• •
Therefore the body of a do loop will execute at least one time The do while is an exit control loop statement.
4.3.3 The for Statement The for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false. for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration Example: public class ListCharacters { public static void main(String[] args) { for( char c = 0; c < 128; c++) if (c != 26 ) // ANSI Clear screen System.out.println("value: " + (int)c + " character: " + c); } }
www.arihantinfo.com
4.4 The comma operator Comma operator is used to separate definitions and function arguments public class CommaOperator { public static void main(String[] args) { for(int i = 1, j = i + 10; i < 5;i++, j = i * 2) { System.out.println("i= " + i + " j= " + j); }}}
4.5 The break Statement The Java break statement causes the Java interpreter to transfer the flow of execution to the end of an enclosing statement. In other words, it is used to break out of a do, for, switch, or while statement. The syntax of the Java break statement is: break; Example: for (int i=0; i < myArray.length; i++) { if (myArray[i] == null; { break; // break out of for loop } } // execution resumes at following statement on break 4.6 The continue statement A Java continue statement is used to terminate the current iteration of a loop and continue with the next iteration. A continue statement can only be used within a do, for, or while loop. The syntax of the Java continue statement is: continue; Example: for (int i=0; i < myArray.length; i++) { if (myArray[i] == null; { continue; // skips remainder of loop and begins next iteration } myMethod (myArray[i]); // do something with a non-null myArray[i] }
www.arihantinfo.com
The different types of looping statements vary in how the continue statement begins a new iteration. •
do loop: On encountering a continue statement, the Java interpreter jumps to the bottom of the do loop. Then, it evaluates the test condition to determine whether to begin a new iteration.
•
for loop: On encountering a continue statement, the Java interpreter begins at the top of the loop in the for statement. First, it evaluates the update expression, e.g. i++. Then, it evaluates the test expression, e.g. i < myArray.length. The important thing is that the update expression is evaluated.
•
while loop: On encountering a continue statement, the Java interpreter begins at the top of the loop in the while statement. Then, it evaluates the test condition to determine whether to begin a new iteration.
www.arihantinfo.com
UNIT 5: CLASSES AND OBJECTS
5.1Classes 5.1.1 The class Declaration 5.1.2 Declaring a class’s Superclass 5.1.3 Listing the interface implemented by a class 5.1.4 Summary of a class Declaration 5.2Declaring Member Variables 5.3Declaring Constants 5.4The Method Declaration 5.5Object Creation and Constructors 5.5.1 Object Creation 5.5.2 Constructor 5.6Controlling access to member of a class 5.6.1 Private 5.6.2 Protected 5.6.3 Public 5.7Subclasses and Inheritance 5.7.1 Definition 5.7.2 Creating Subclasses 5.8Overriding Methods 5.9Final classes and Methods 5.9.1 Final Classes 5.9.2 Final Methods 5.10 Abstract classes and Methods 5.10.1 Abstract classes 5.10.2 Abstract Methods
5.1 Classes A class is a blueprint or prototype that you can use to create many objects. classDeclaration { memberVariableDeclarations methodDeclarations }
5.1.1 The Class Declaration At minimum, a class declaration must contain the class keyword and the name of the class that you are defining: class NameOfClass { ... }
www.arihantinfo.com
5.1.2 Declaring a Class's Superclass In Java, every class has a superclass. If you do not specify a superclass for your class, it is assumed to be the Object class (declared in java.lang). class NameOfClass extends SuperClassName { ... } A subclass inherits variables and methods from its superclass. 5.1.3 Listing the Interfaces Implemented by a Class An interface declares a set of methods and constants without specifying the implementation for any of the methods. When a class claims to implement an interface, it's claiming to provide implementations for all of the methods declared in the interface. class ImaginaryNumber extends Number implements Arithmetic { ... } 5.1.4 Summary of a Class Declaration [ modifiers ] class ClassName [ extends SuperClassName ] [ implements InterfaceNames ] { ... } •
modifiers declare whether the class is public, abstract, or final
•
ClassName sets the name of the class you are declaring
•
SuperClassName is the name of ClassName's superclass
•
InterfaceNames is a comma-delimited list of the interfaces implemented
5.2 Declaring Member Variables class IntegerClass { int anInteger; . . . // define methods here . . .} In short, a member variable declaration looks like this: [accessSpecifier] [static] [final] type variableName accessSpecifier defines which other classes have access to the variable. You control access to methods using the same specifiers, so Controlling Access to Members of a Class covers how you can control access to both member variables and methods. static indicates that the variable is a class member variable as opposed to an instance member variable. You also use static to declare class methods. Instance and Class Members talks about declaring instance and class variables and writing instance and class methods.
www.arihantinfo.com
5.3 Declaring Constants class Avo { final double AVOGADRO = 6.023e23; }
5.4 The Method Declaration returnType methodName() { . . . } Passing Information into a Method The Method Body ... boolean isEmpty() { if (topelement == STACK_EMPTY) return true; else return false; } 5.5 Object Creation and Constructor 5.5.1 Object Creation Although most of the design work in object-oriented programming is creating classes, you don't really benefit from that work until you create instances (objects) of those classes. To use a class in a program, you must first create an instance of it. 5.5.2 Constructor Before getting into the details of how to create an object, there is an important method you need to know about: the constructor. When you create an object, you typically want to initialize its member variables. The constructor is a special method you can implement in all your classes; it allows you to initialize variables and perform any other operations when an object is created from the class. The constructor is always given the same name as the class. The following Listing contains the complete source code for the Alien class, which contains two constructors. Listing . The Alien class. class Alien extends Enemy { protected Color color; protected int energy; protected int aggression; public Alien() { color = Color.green; energy = 100; aggression = 15; }
www.arihantinfo.com
public Alien(Color c, int e, int a) { color = c; energy = e; aggression = a; } public void move() { // move the alien } public void move(int x, int y) { // move the alien to the position x,y } public void morph() { if (aggression < 10) { // morph into a smaller size } else if (aggression < 20) { // morph into a medium size } else { // morph into a giant size } } } The Alien class uses method overloading to provide two different constructors. The first constructor takes no parameters and initializes the member variables to default values. The second constructor takes the color, energy, and aggression of the alien and initializes the member variables with them. As well as containing the new constructors, this version of Alien uses access modifiers to explicitly assign access levels to each member variable and method. This is a good habit to get into.
5.6 Controlling Access to Members of a Class Specifier class subclass package world ----------------------------------------------------private X protected public package
X X X
X* X
X X X
X
5.6.1 Private The most restrictive access level is private. A private member is accessible only to the class in which it is defined.
www.arihantinfo.com
class Alpha { private int iamprivate; private void privateMethod() { System.out.println("privateMethod"); } } class Beta { void accessMethod() { Alpha a = new Alpha(); a.iamprivate = 10; // illegal a.privateMethod(); // illegal }} 5.6.2 Protected It allows the class itself, subclasses, and all classes in the same package to access the members. package Greek; class Alpha { protected int iamprotected; protected void protectedMethod() { System.out.println("protectedMethod"); } } package Greek; class Gamma { void accessMethod() { Alpha a = new Alpha(); a.iamprotected = 10; // legal a.protectedMethod(); // legal } } package Latin; class Delta extends Alpha { void accessMethod(Alpha a, Delta d) { a.iamprotected = 10; a.protectedMethod(); // illegal d.iamprotected = 10; d.protectedMethod(); // legal } }
5.6.3 Public Any class, in any package, has access to a class's public members. package Greek; class Alpha { public int iampublic; public void publicMethod() { System.out.println("publicMethod");
www.arihantinfo.com
} } import Greek.*; package Roman; class Beta { void accessMethod() { Alpha a = new Alpha(); a.iampublic = 10; // legal a.publicMethod(); // legal } }
5.7 Subclasses and Inheritance The derived class is called a subclass. The class from which its derived is called the superclass.
In Java all classes must be derived from some class. The top-most class, the class from which all other classes are derived, is the Object class defined in java.lang:
www.arihantinfo.com
5.7.1 Definition: A subclass is a class that derives from another class. It subclass inherits state and behavior in the form of variables and methods from all of its ancestors. It can just use the items inherited from its superclass as is, or the subclass can modify or override it. So, as you drop down in the hierarchy, the classes become more and more specialized. 5.7.2 Creating Subclasses To declare a subclass you would write: class SubClass extends SuperClass { . . . } Note:- A Java class can have only one direct superclass. Java does not support multiple inheritance. Member variables defined in the subclass hide member variables of the same name in the superclass. Consider this superclass and subclass pair: class Super { void addNum(int x,int y) { int sum; sum=x + y; System.out.println(“Sum of Number = “+sum); } void display() { System.out.println(“I am from SuperClass”); } } class Sub extends Super { public static void main(String args[]) {
www.arihantinfo.com
Sub s1 = new Sub(); s1.display(); s1.addNum(10,20); }} Output is : I am from SuperClass Sum of Number = 30 5.8Overriding Methods The following example shows method overriding. When an object’s method is called, java looks for the method definition in the object’s class. If it can not find, then it checks one level up in the hierarchy of classes. Consider the case when the same method name is used in both the superclass and superclass with the same signature (same number of arguments with the same type). Here when the method is called, method defined in the subclass is invoked. The method defined in the super class is overridden. It is now hidden for the objects of the subclass. If the method defined in the super class has to be used, then the super keyword can be used along with the name of the method. In the example below, the method display() and this.display() will invoke method display() of the subclass. The call super.display() will invoke the method display() of the super class. This program uses the super class coded earlier as the program Super.java class OverRide extends Super { void access() { System.out.println(“Displays from a different palce”); //display method of subclass display(); //display method of superclass super.display(); //display method of subclass this.display(); } void display() { System.out.println(“I am from SubClass”); } public static void main(String args[]) { OverRide s1= new OverRide(); s1.access(); } } 5.9 Final Classes and Methods 5.9.1
Final Classes
You can declare that your class is final; that is, that your class cannot be subclassed. There are (at least) two reasons why you might want to do this: security reasons and design reasons.
www.arihantinfo.com
5.9.2
Final Methods
You can use the final keyword in a method declaration to indicate to the compiler that the method cannot be overridden by subclasses. 5.10 Abstract Classes and Methods 5.10.1 Abstract Classes Classes, which implement abstract concepts and should not be instantiated, are called abstract classes. An abstract class is a class that can only be subclassed--it cannot be instantiated. 5.10.2 Abstract Methods An abstract class may contain abstract methods, that is, methods with no implementation. In this way, an abstract class can define a complete programming interface thereby providing its subclasses with the method declarations for all of the methods necessary to implement that programming interface. Example: //use of abstract class and method abstract class AbstractClass { public void printHello() { System.out.println(“Printing from abstract class”); } abstract void printMe(); } class TestAbstract extends AbstractClass { public void printMe() { System.out.println(“Implementing abstract method”); } public static void main(String args[]) { TestAbstract p =new TestAbstract(); p.printHello(); p.printMe(); } } Architectural advantage Abstract classes provide a way to represent objects at a conceptual generic level. In a graphic library, you can create an abstract class to represent a generic graphic object and a method for drawing it. This method is then only implemented on the derived classes.
www.arihantinfo.com
www.arihantinfo.com
UNIT 6: PACKAGES AND INTERFACES
6.1Packages 6.1.1 How to create your own packages 6.2Classpath 6.3The meaning of static 6.4Cleanup: Finalization and Garbage collection 6.5Forcing Finalization and Garbage collection 6.6Interfaces 6.6.1 What is an interface 6.6.2 The interface Declaration 6.6.3 Multiple Extension (Inheritance) 6.6.4 Implementing an interface 6.6.5 Using an interface as a type 6.6.6 Interfaces verses abstract classes
6.1 Packages: A package is a collection of classes and interfaces of similar nature. For example java.io package contains classes and interfaces for various kinds of input and output. Package defines a boundary to see how classes and interfaces interact with one another. Therefore it also acts as a mode of protection. Java language programs automatically import all classes in the java.lang package. Packages gives us the following advantages : Advantages: •
It makes classes easier to find and use.
•
It avoids naming conflicts.
To import classes from a package, import command is used. Import java.io.*; Import pack.subpack.MyClass; In the first case all public classes in the package java.io are available. In the second case only class having the name pack.subpack.MyClass is available for use. 6.1.1
How to Create Your Own Packages
The first statement in a java program should be a package statement. package pack.subpack; Example : package graphics; interface Draggable { . . . } class Circle { . . . } class Rectangle { . . . } The .class files generated must be placed in a directory named graphics somewhere in your CLASSPATH.
www.arihantinfo.com
6.2 CLASSPATH A list of directories that indicate where on the file system you've installed various compiled Java classes and interfaces. Java searches your CLASSPATH for a directory whose name matches the package name of which the class is a member. Note: If you don't specify a package, your classes and interfaces become members of the default package, which has no name. 6.3 The meaning of static With the this keyword in mind, you can more fully understand what it means to make a method static. It means that there is no this for that particular method. You cannot call non-static methods from inside static methods1 (although the reverse is possible), and you can call a static method for the class itself, without any object. In fact, that’s primarily what a static method is for. It’s as if you’re creating the equivalent of a global function (from C). Except global functions are not permitted in Java, and putting the static method inside a class allows it access to other static methods and to static fields. Some people argue that static methods are not object-oriented since they do have the semantics of a global function; with a static method you don’t send a message to an object, since there’s no this. This is probably a fair argument, and if you find yourself using a lot of static methods you should probably rethink your strategy. However, statics are pragmatic and there are times when you genuinely need them, so whether or not they are “proper OOP” should be left to the theoreticians. Indeed, even Smalltalk has the equivalent in its “class methods.” 6.4 Cleanup: Finalization and Garbage collection Programmers know about the importance of initialization, but often forget the importance of cleanup. After all, who needs to clean up an int? But with libraries, simply “letting go” of an object once you’re done with it is not always safe. Of course, Java has the garbage collector to reclaim the memory of objects that are no longer used. Now consider a very unusual case. Suppose your object allocates “special” memory without using new. The garbage collector knows only how to release memory allocated with new, so it won’t know how to release the object’s “special” memory. To handle this case, Java provides a method called finalize( ) that you can define for your class. Here’s how it’s supposed to work. When the garbage collector is ready to release the storage used for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the object’s memory. So if you choose to use finalize( ), it gives you the ability to perform some important cleanup at the time of garbage collection.
1
The one case in which this is possible occurs if you pass a reference to an object into the static method. Then, via the reference (which is now effectively this), you can call nonstatic methods and access non-static fields. But typically if you want to do something like this you’ll just make an ordinary, non-static method.
www.arihantinfo.com
This is a potential programming pitfall because some programmers, especially C++ programmers, might initially mistake finalize( ) for the destructor in C++, which is a function that is always called when an object is destroyed. But it is important to distinguish between C++ and Java here, because in C++ objects always get destroyed (in a bug-free program), whereas in Java objects do not always get garbage-collected. Or, put another way: Garbage collection is not destruction. If you remember this, you will stay out of trouble. What it means is that if there is some activity that must be performed before you no longer need an object, you must perform that activity yourself. Java has no destructor or similar concept, so you must create an ordinary method to perform this cleanup. For example, suppose in the process of creating your object it draws itself on the screen. If you don’t explicitly erase its image from the screen, it might never get cleaned up. If you put some kind of erasing functionality inside finalize( ), then if an object is garbage-collected, the image will first be removed from the screen, but if it isn’t, the image will remain. So a second point to remember is: Your objects might not get garbage-collected. You might find that the storage for an object never gets released because your program never nears the point of running out of storage. If your program completes and the garbage collector never gets around to releasing the storage for any of your objects, that storage will be returned to the operating system en masse as the program exits. This is a good thing, because garbage collection has some overhead, and if you never do it you never incur that expense. What is finalize( ) for? You might believe at this point that you should not use finalize( ) as a general-purpose cleanup method. What good is it? A third point to remember is: Garbage collection is only about memory. That is, the sole reason for the existence of the garbage collector is to recover memory that your program is no longer using. So any activity that is associated with garbage collection, most notably your finalize( ) method, must also be only about memory and its deallocation. Does this mean that if your object contains other objects finalize( ) should explicitly release those objects? Well, no—the garbage collector takes care of the release of all object memory regardless of how the object is created. It turns out that the need for finalize( ) is limited to special cases, in which your object can allocate some storage in some way other than creating an object. But, you might observe, everything in Java is an object so how can this be? It would seem that finalize( ) is in place because of the possibility that you’ll do something Clike by allocating memory using a mechanism other than the normal one in Java. This can happen primarily through native methods, which are a way to call non-Java code from Java. (Native methods are discussed in Appendix B.) C and C++ are the only languages currently supported by native methods, but since they can call subprograms in other languages, you can effectively call anything. Inside the non-Java code, C’s malloc( ) family of functions might be called to allocate storage, and unless you call free( ) that storage will not be released, causing a memory leak. Of course, free( ) is a C and C++ function, so you’d need to call it in a native method inside your finalize( ).
www.arihantinfo.com
After reading this, you probably get the idea that you won’t use finalize( ) much. You’re correct; it is not the appropriate place for normal cleanup to occur. So where should normal cleanup be performed? 6.5 Forcing Finalization and Garbage Collection System.runFinalization(): This method calls the finalize() methods on all objects that are waiting to be garbage collected. System.gc(): It asks the garbage collector to run at any time by calling System's gc()
method. //: c04:Garbage.java // Demonstration of the garbage // collector and finalization class Chair { static boolean gcrun = false; static boolean f = false; static int created = 0; static int finalized = 0; int i; chair() { i = ++created; if(created == 47) System.out.println("Created 47"); } public void finalize() { if(!gcrun) { // The first time finalize() is called: gcrun = true; System.out.println( "Beginning to finalize after " + created + " Chairs have been created"); } if(i == 47) {
www.arihantinfo.com
System.out.println( "Finalizing Chair #47, " + "Setting flag to stop Chair creation"); f = true; } finalized++; if(finalized >= created) System.out.println( "All " + finalized + " finalized"); } } public class Garbage { public static void main(String[] args) { // As long as the flag hasn't been set, // make Chairs and Strings: while(!Chair.f) { new Chair(); new String("To take up space"); } System.out.println( "After all Chairs have been created:\n" + "total created = " + Chair.created + ", total finalized = " + Chair.finalized); // Optional arguments force garbage // collection & finalization: if(args.length > 0) { if(args[0].equals("gc") || args[0].equals("all")) { System.out.println("gc():");
www.arihantinfo.com
System.gc(); } if(args[0].equals("finalize") || args[0].equals("all")) { System.out.println("runFinalization():"); System.runFinalization(); } } System.out.println("bye!"); } } ///:~ The above program creates many Chair objects, and at some point after the garbage collector begins running, the program stops creating Chairs. Since the garbage collector can run at any time, you don’t know exactly when it will start up, so there’s a flag called gcrun to indicate whether the garbage collector has started running yet. A second flag f is a way for Chair to tell the main( ) loop that it should stop making objects. Both of these flags are set within finalize( ), which is called during garbage collection. Two other static variables, created and finalized, keep track of the number of Chairs created versus the number that get finalized by the garbage collector. Finally, each Chair has its own (non-static) int i so it can keep track of what number it is. When Chair number 47 is finalized, the flag is set to true to bring the process of Chair creation to a stop. All this happens in main( ), in the loop while(!Chair.f) { new Chair(); new String("To take up space"); } You might wonder how this loop could ever finish, since there’s nothing inside the loop that changes the value of Chair.f. However, the finalize( ) process will, eventually, when it finalizes number 47. The creation of a String object during each iteration is simply extra storage being allocated to encourage the garbage collector to kick in, which it will do when it starts to get nervous about the amount of memory available. When you run the program, you provide a command-line argument of “gc,” “finalize,” or “all.” The “gc” argument will call the System.gc( ) method (to force execution of the garbage collector). Using the “finalize” argument calls System.runFinalization( ) which—in theory— will cause any unfinalized objects to be finalized. And “all” causes both methods to be called.
www.arihantinfo.com
The behavior of this program and the version in the first edition of this book shows that the whole issue of garbage collection and finalization has been evolving, with much of the evolution happening behind closed doors. In fact, by the time you read this, the behavior of the program may have changed once again. If System.gc( ) is called, then finalization happens to all the objects. This was not necessarily the case with previous implementations of the JDK, although the documentation claimed otherwise. In addition, you’ll see that it doesn’t seem to make any difference whether System.runFinalization( ) is called. However, you will see that only if System.gc( ) is called after all the objects are created and discarded will all the finalizers be called. If you do not call System.gc( ), then only some of the objects will be finalized. In Java 1.1, a method System.runFinalizersOnExit( ) was introduced that caused programs to run all the finalizers as they exited, but the design turned out to be buggy and the method was deprecated. This is yet another clue that the Java designers were thrashing about trying to solve the garbage collection and finalization problem. We can only hope that things have been worked out in Java 2. The preceding program shows that the promise that finalizers will always be run holds true, but only if you explicitly force it to happen yourself. If you don’t cause System.gc( ) to be called, you’ll get an output like this: Created 47 Beginning to finalize after 3486 Chairs have been created Finalizing Chair #47, Setting flag to stop Chair creation After all Chairs have been created: total created = 3881, total finalized = 2684 bye! Thus, not all finalizers get called by the time the program completes. If System.gc( ) is called, it will finalize and destroy all the objects that are no longer in use up to that point. Remember that neither garbage collection nor finalization is guaranteed. If the Java Virtual Machine (JVM) isn’t close to running out of memory, then it will (wisely) not waste time recovering memory through garbage collection. 6.6 Interfaces 6.6.1 What is an Interface? It is a promise that your class will implement certain methods with certain signatures. In other words an interface is a collection of method definitions (without implementations) and constant values. You even use the keyword implements to indicate that your class will keep these promises. Advantages: •
Capturing similarities between unrelated classes without forcing a class relationship.
•
Declaring methods that one or more classes are expected to implement.
www.arihantinfo.com
•
Revealing an object's programming interface without revealing its class (objects such as these are called anonymous objects and can be useful when shipping a package of classes to other developers)
Defining an Interface The interface declaration and the interface body; interfaceDeclaration { interfaceBody } 6.6.2 The interface Declaration: [public] interface InterfaceName [extends listOfSuperInterfaces] { ... } interface Collection { int MAXIMUM = 500; void add(Object obj); void delete(Object obj); Object find(Object obj); int currentCount(); } 6.6.3 Multiple Extensions (Inheritance) An interface can extend multiple interfaces (while a class can only extend one), and an interface cannot extend classes. 6.6.4 Implementing an Interface To use an interface, you write a class that implements the interface. Definition: To implement an interface a class has to provides a method implementation for all of the methods declared within the interface. class FIFOQueue implements Collection { ... void add(Object obj) { . . . } ... }
6.6.5
Using an Interface as a Type
An interface is a new reference data type. You can use interface names anywhere you'd use any other type name: variable declarations, method parameters and so on: interface CellAble { void sdraw();
www.arihantinfo.com
void toString(); void toFloat(); } class Row { ... private CellAble[] contents; ... void setObjectAt(CellAble ca, int index) { ... } ... } Any object that implemented the callable interface can be contained in the contents array and can be passed into the setObjectAt () method
6.6.6 Interfaces verses abstract classes While an interface is used to specify the form that something must have, it does not actually provide the implementation for it. In this sense, an interface is a little like an abstract class that must be extended in exactly the manner that its abstract methods specify. •
An abstract class is an incomplete class that requires further specialization. An interface is just a specification or prescription for behavior.
•
An interface does not have any overtones of specialization that are presented with inheritance.
•
A class can implement several interfaces at once, whereas a class can extends only one parent class.
www.arihantinfo.com
UNIT 7: INTRODUCTION TO APPLET PROGRAMMING
7.1What are Applets 7.1.1 What applet can do 7.1.2 What applet can not do 7.2Types of an Applet 1.2.1 Local Applet 1.2.2 Remote Applet 7.3Lifecycle of an Applet 7.4Passing parameters to an Applet 7.1 What are APPLETS ? An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included. When you use a Java technology-enabled browser to view a page that contains an applet, the applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM). In other words we can define an applet is a java program that can be embedded in a web page. Java application is run by using a java interpreter. Applets are run on any browser that support java. Applets can also be tested using the appletviewer tool included in the java development kit. In order to run an applet it must be included in a web page, using HTML tags. When a user browses a web page containing an applet, the browser downloads the applet from the web server and runs it on the user’s system. Applets have certain restrictions put on them.
7.1.1 What applets can do
Applets can make network connections to the host they came from.
Applets running within a Web browser can easily cause HTML documents to be displayed.
Applets can invoke public methods of other applets on the same page.
Applets that are loaded from the local file system have none of the restrictions that applets loaded over the network do.
Although most applets stop running once you leave their page, they don't have to.
7.1.2 What applets can not do
An applet can't load libraries or define native methods.
It can't ordinarily read or write files on the host that's executing it.
It can't make network connections except to the host that it came from.
It can't start any program on the host that's executing it.
www.arihantinfo.com
It can't read certain system properties. Windows that an applet brings up look different than windows that an application brings up.
All applets are subclasses of the Applet class in the java.applet package. Applets do not have main() method. All applets must be declared public. 7.2 Types of an Applet Basically, your Web pages can contain two types of applets: local and remote. 7.2.1 Local Applets A local applet is one that is stored on your own computer system. When your Web page must find a local applet, it doesn't need to retrieve information from the Internet-in fact, your browser doesn't even need to be connected to the Internet at that time. As you can see in example, a local applet is specified by a path name and a file name.
Specifying a Local Applet. In this example the codebase attribute specifies a path name on your system for the local applet, whereas the code attribute specifies the name of the byte-code file that contains the applet's code. The path specified in the codebase attribute is relative to the folder containing the HTML document that references the applet.
www.arihantinfo.com
7.2.2 Remote Applets A remote applet is one that is located on another computer system. This computer system may be located in the building next door or it may be on the other side of the world-it makes no difference to your Java-compatible browser. No matter where the remote applet is located, it's downloaded onto your computer via the Internet. Your browser must, of course, be connected to the Internet at the time it needs to display the remote applet. To reference a remote applet in your Web page, you must know the applet's URL (where it's located on the Web) and any attributes and parameters that you need to supply in order to display the applet correctly. If you didn't write the applet, you'll need to find the document that describes the applet's attributes and parameters. This document is usually written by the applet's author. Example given below shows how to compose an HTML tag that accesses a remote applet.
Specifiying a Remote Applet. The only difference between local and remote is the value of the codebase attribute. In the first case, codebase specifies a local folder, and in the second case, it specifies the URL at which the applet is located.
7.3 Lifecycle of an Applet
www.arihantinfo.com
There are 4 important phases in the life cycle of an applet. 1. 2.
3. 4.
Initialization occurs when the applet is loaded. This is implemented by the init() method. To implement a specific initialization process such as setting up initial state, loading images or fonts, init() method is overridden. An applet is started after it is initialized. Starting can occur if it is in a stopped state. The method start() can be overridden to implement start operation. An applet is stopped when the user goes to a different web page and comes back to the page containing applet. Initialization occurs only once whereas starting occurs any number of times. stopping occurs when the user leaves the page containing the applet or when an applet stops itself by calling stop() method. Destruction is done using destroy() method. This method perform cleanup process when the browser exits.
Begin (Load Applet)
Born
Initialization
start() Running
stop ( )
Idle
Stopped
start ( ) Display
destroy ( ) Paint ( ) Dead Destroyed
End
Exit of Browser
An applet’s state transition diagram
import java.awt.*; import java.applet.*; /* */ public class Sample extends Applet { String msg; //set the foreground and background colors. public void init() { setBackground(Color.cyan); setForeground(Color.red); msg=”Inside init() – “; } //Initialize the string to be displayed.
www.arihantinfo.com
public void start() { msg +=”Inside start() –“; } //Display msg in applet window. public void paint(Graphics g) { msg += “Inside paint() – “; g.drawString(msg,10,30); } public void stop() { msg=”Inside Stop -- “; } public void destroy() { System.out.println(“Inside Destroy”); } } 7.4 Passing parameters to an applet. The parameters are passed to applets by using the attribute PARAM in the applet tag. The example below shows passing of parameters. TestParam.java import java.awt.*; import java.applet.Applet; public class TestParam extends Applet { Font f = new Font(“Arial”,Font.BOLD,24); String s; public void paint(Graphics g) { g.setFont(f); g.setColor(Color.blue); g.drawstring(s,10,50); } public void init() { s= getParameter(“s”); if(s==null) s=”Null value returned”; } } The html code for viewing the applet is shown below. TestApplet.htm My page This page shows use of Applet
www.arihantinfo.com
In order to view the applet, an HTML code has to be written. This code contains tag. The above code uses the tag. It has three attributes. • CODE – Specifies the name of the applet’s main class file. • WIDTH – Specifies the width of the applet window on the Web Page. • HEIGHT – Specifies the height of the applet window. Other attribute that could be added to the applet tag are • ALIGN – This could be set to LEFT,RIGHT,MIDDLE,TOP • HSPACE – Controls the horizontal space to the left and right of the applet. • VSPACE - Controls the vertical space above and below the applet. • CODEBASE – Indicates an alternate folder or alternate web site for the browser to locate the applet. • ALT – Specifies the text to be display if the browser understands the applet tag, but can’t run Java applets. The applet can be viewed by typing appletviewer TestApplet.htm at the command prompt. Adding graphics and colors import java.awt.*; import java.applet.*; public class Face extends Applet { public void paint (Graphics g) { g.drawOval (40, 40, 120, 150); //Head g.drawOval (57, 75, 30, 20); //Left eye g.drawOval (110, 75, 30, 20); //Right eye g.fillOval (68, 81, 10, 10); //Pupil (left) g.fillOval (121, 81, 10, 10); //Pupil (right) g.drawOval (85, 100, 30, 30); //Nose g.fillArc (60, 125, 80, 40, 180, 180); //Mouth g.drawOval (25, 92, 15, 30); //Left ear g.drawOval (160, 92, 15, 30); //Right ear } } import java.awt.*; import java.applet.*; public class Graph extends Applet { public void paint (Graphics g) { g.setColor(Color.blue);
www.arihantinfo.com
g.drawLine (5, 5, 100,100); g.drawRect (10, 10, 60, 75); g.fillRect (100, 10, 60, 50); g.drawRoundRect (190, 10, 60, 50, 15, 15); g.fillRoundRect (70, 90, 140, 100, 30, 40); } }
www.arihantinfo.com
Unit 8 Programming the Abstract Windowing Toolkit (AWT) 8.1Introduction of AWT 8.2AWT Component Hierarchy 8.3How to Add a Component to a Container 8.4AWT Component 8.4.1 Labels 8.4.2 Buttons 8.4.3 Checkbox 8.4.4 TextFields 8.4.5 TextAreas 8.4.6 Choice lists 8.4.7 Scrolling Lists 8.5Event Handling 8.5.1 Introduction 2.5.2 Event Listener Interfaces 8.6How to implement event handlers: 8.6.1 Buttons 8.6.2 Canvases 8.6.3 Checkboxes 8.6.4 Choices 8.6.5 Lists 8.6.6 ScrollPanes 8.6.7 TextComponent 8.6.8 Menus 8.7AWT Containers 8.7.1 Frames 8.7.2 Panels 8.7.3 Dialogs 8.8Layouts 8.8.1 The FlowLayout Class 8.8.2 The BoderLayout Class 8.8.3 The GridLayout Class 8.8.4 The GridBagLayout Class 8.8.5 The CardLayout class 8.8.6 Combining Layouts with Nested Panels 8.9Using Adapters to Handle Events 8.1 Introduction of AWT The Abstract Windowing Toolkit, also called as AWT is a set of classes, enabling the user to create a user friendly, graphical user Interface (GUI). It will also facilitate receiving user input from the mouse and keyboard. 8.2 AWT Component Hierarchy:
www.arihantinfo.com
AWT MenuComponent:
8.3 How to Add a Component to a Container For any Component object except a Window to display itself onscreen, you must first add it to a Container object. The Container class defines three methods for adding components: •
add(Component comp) method simply requires that you specify the component to add.
•
add(Component comp, int ind) method lets you add an argument specifying the integer
position at which the component should be added. •
add(String pos, Component comp) method has as first argument a layout manager-dependent
string that specifies the component's position to the layout manager. The component can be removed by calling the remove method of the Container class. void remove(Component obj)
The user interface consists of the following three. • Component – Anything that can be put on the interface. This includes buttons, check boxes, pop-up menus, text fields.
www.arihantinfo.com
• •
Containers – This is a component that can contain other components. Layout managers – These define how the components will be arrangesd in a container.
The statement import java.awt.*; imports all the components, containers and layout managers necessary for designing the user interface. The AWT supplies the following components. • Labels • Buttons • Checkboxes • Choice • Scrollbars • Text editing 8.4 AWT Components 8.4.1 Labels Labels display non editable text. To create a label use one of the following. Label () – creates an empty label. Label (string) – creates a label with the given string. Label (string, int) – creates a label with the given string and right, left or center alignment. 8.4.2 Buttons Clickable buttons can be created from the Button class. You can create a button by using either of the following. • Button () – Creates a button without any label. Use setLabel(string) to display a text on the button. • Button (string) – Creates a button with the given string as the label. 8.4.3 Checkboxe They are labeled or unlabeled boxes that can be either checked off or empty. They are used for selecting some option. Use one of the following to create them. • Checkbox () – Creates a checkbox without any label. • Checkbox (string) – Creates a labeled checkbox. When many checkboxes are there any number of them can be checked or unchecked. Checkboxes can be organized into groups so that only one of them can be checked at a time. The following statement creates a checkbox group. CheckboxGroup mygroup = new CheckboxGroup(); To create a checkbox, belonging to this group, use the following statement. Checkbox c1 = new Checkbox (“Manipal”, mygroup, true); This program creates label, checkbox and buttons. import java.awt.*; import java.applet.Applet;
www.arihantinfo.com
public class AddUserInterface extends Applet { Label lb = new Label (“Choose one”, Label.CENTER); Checkbox c1 = new Checkbox (“Delhi”); Checkbox c2 = new Checkbox (“Mumbai”); Button b1 = new Button (“Submit”); Button b2 = new Button (“Cancel”); public void init() { add(lb);add(c1); add(c2);add(b1); add(b2); } 8.4.4 TextFields Textfield is an editable component. Text field can be created by using one of the following • TextField () – Creates an empty text field. • TextField (string) – Creates a text field with the specified string. • TextField (string, int) – Creates a text field with specified string and specified width. The TextField class has several useful methods. • The getText() method returns the text in the field. • The setText(string) method fills the field with the string. • The setEditable (Boolean) method decides wheteher the field should be editable or not depending upon the Boolean value. • The isEditable () method returns a Boolean value indicating whether the filed is editable or not. 8.4.5 TextAreas These create • • • •
are editable text fields having more than one line of input. Use one of following to a text area. TextArea () – creates an empty text area. TextArea (rows, characters) – Creates a text area of rows specified and width to accommodate the characters specified. TextArea (string) TextArea (string, rows, characters)
The methods available in case of Text field can also be used here. In addition to that the following methods could be used. •
The insert(string, charindex) method inserts the indicated string at the position indicated by the second argument. • The replace(string, startpos, endpos) method replaces the text between the given integer positions with the indicated string. • The example below shows the use of TextField and Text Area. //applet to show the use of text field and text area import java.awt.*; import java.applet.Applet; public class UseText extends Applet { Label l1 = new Label(“Enter name”,Label.CENTER); TextField t1 = new TextField(10); Label l2 = new Label(“Enter message”,Label.CENTER);
www.arihantinfo.com
TextArea t2 = new TextArea(5,10); Button b1 = new Button (“Submit”); public void init() { add(l1);add(t1); add(l2);add(t2); add(b1);add(b2); } 8.4.6 Choice lists They are also called as pop up lists. They enable a single item to be chosen from a list of items. Choice list is created and used as follows: • Create an object of the class Choice. • Add items to the list by using the method addItem(item) in the choice class. • Add the list as you do with any other component using the add(component) method. The choice class has the following methods available: • getItem (index) – Returns text of the list item at the index position specified in the argument. • getItemCount () – Returns the number of items in the list. • getSelectedItem () – Returns the index position of the currently selected item. • getSelectedIndex () – Returns the index position of the currently selected item. • select (pos) – Selects the item at the indicated index position. • select (text) – Selects the first in the list with the given text. 8.4.7 Scrolling Lists These are created from the list class. These are similar to choice lists. But here you can choose more than one item at a time. Scrolling lists do not pop up. Multiple items are displayed at the same time. The list is created by choosing one of the following: • List() – Created an empty scrolling list enabling only one item to be selected at a time. • List (item, Boolean) – Created a scrolling list with number of items equal to the first argument. The Boolean argument allows multiple selection is set to true. • AddItem () – method is used to add item to the list. The example below shows the use of choice list and scrolling list. import java.awt.*; import java.applet.*; public class UseList extends Applet { Choice c = new Choice (); List l = new List (3, true); Button b1 = new Button(“Submit”); Button b2 = new Button(“Cancel”); public void init() { c.addItem(“Sachin”); c.addItem(“Lara”); c.addItem(“Klusner”); add(l); add(b1);add(b2); } }
www.arihantinfo.com
8.5 Event Handling 8.5.1 Introduction The earlier version of Java, that is, JDK 1.0 used hierarchical event model, but later in JDK 1.1 version, the Java event model is entirely changed to event delegation model. Basics of Event Handling When you are working with the programs having GUIs, you have to know how to handle the events generated by the components. To do this, there are mainly four steps to be followed: 1. Declare and instantiate event sources (or components) such as buttons, menus, choices etc. 2. Implement an interface to provide the event handler that responds to event source activity. 3. Register this event handler with the event source. 4. Add the event source to the container like applet, frame, panel etc. Events An event is the encapsulation of some user input delivered to the application asynchronously. The java.awt.AWTEvent is the root class of all AWT events. From any AWTEvent you can get the object that was the event source by invoking getSource() method. AWTEvent is subclassed as : ActionEvent, WindowEvent, ItemEvent, KeyEvent, MouseEvent, TextEvent, etc. 8.5.2 Event Listener Interfaces Event handling is achieved through the use of listener interfaces, defined in the package java.awt.event. In java we have a number of built in interfaces as listeners for different types of event handling. The table below lists listener interfaces and the event sources which uses them. Interface Events Generated by ActionListener Button, List, MenuItem, TextField. AdjustmentListener Scrollbar ItemListener Checkbox, CheckboxMenuItem, Choice, List. TextListener TextComponent ComponentListener Component ContainerListener Component FocusListener Container KeyListener Component MouseListener Component MouseMotionListener Component WindowListener Window These interfaces declare one or more methods each of which handle a specific event Adapter classes will be discussed later on . Listener Interface Adapter Class Methods ActionListener
none
actionPerformed
www.arihantinfo.com
AdjustmentListener
none
AdjustmentValueChanged componentHidden
ComponentListener
ComponentAdapter
componentMoved componentResized componentShown
ContainerListener
ContainerAdapter
FocusListener
FocusAdapter
ItemListener
none
componentAdded componentRemoved focusGained focusLost ItemStateChanged keyPressed
KeyListener
KeyAdapter
keyReleased keyTyped mouseClicked mouseEntered
MouseListener
MouseAdapter
mouseExited mousePressed mouseReleased
MouseMotionListener
MouseMotionAdapter
TextListener
none
mouseDragged mouseMoved TextValueChanged windowActivated windowClosed windowClosing
WindowListener
WindowAdapter
windowDeactivated windowDeiconified windowIconified windowOpened
8.6 How to implement event handlers: 1. Code declaring that the class implements a listener interface : public class MyClass implements ActionListener { 2. Code that registers an instance of the event handling class as a listener: someComponent.addActionListener(instanceOfMyClass); 1. The implementation of the methods in the listener interface:
www.arihantinfo.com
public
void ...//code
actionPerformed(ActionEvent that reacts to
the
e)
{ action...
}
8.6.1 Buttons The Button class provides a default button implementation. A button is a simple control that generates an action event when the user clicks it.
Code Example: b1 = new Button(); b1.setLabel("Disable middle button"); b1.setActionCommand(DISABLE); b2 = new Button("Middle button"); b3 = new Button("Enable middle button"); b3.setEnabled(false); b3.setActionCommand(ENABLE); //Listen for actions on buttons 1 and 3. b1.addActionListener(this); b3.addActionListener(this); ... public void actionPerformed(ActionEvent e) { String command= e.getActionCommand(); if (command==DISABLE) { //They clicked "Disable middle button" b2.setEnabled(false); b1.setEnabled(false); b3.setEnabled(true); } if (command == ENABLE) { //They clicked "Enable middle button" b2.setEnabled(true); b1.setEnabled(true); b3.setEnabled(false); } } 8.6.2 Canvases The Canvas class exists to be subclassed. It does nothing on its own; it merely provides a way for you to implement a custom Component.
Code Example: class ImageCanvas extends Canvas { Container pappy;
www.arihantinfo.com
Image image; boolean trueSizeKnown = false; Dimension minSize; public ImageCanvas(Image image, Container parent, int w, int h) { if (image == null) { System.err.println("Canvas got invalid image object!"); return; } this.image = image; pappy = parent; minSize = new Dimension(w,h); } public Dimension getPreferredSize() { return getMinimumSize(); } public Dimension getMinimumSize() { return minSize; } public void paint (Graphics g) { if (image != null) { if (!trueSizeKnown) { int width= image.getWidth(this); int height= image.getHeight(this) if ((imageWidth > 0) && (imageHeight > 0)) { trueSizeKnown = true; // Component-initiated resizing. minSize = new Dimension(width,height); setSize(width, height); pappy.validate(); } } g.drawRect(0, 0, minSize.width - 1, minSize.height - 1); g.drawImage(image, 0, 0, this); } } }
8.6.3 Checkboxes Checkboxes are two-state buttons that can be either "on" or "off". When the user clicks a checkbox, the checkbox state changes and it generates an action event.
www.arihantinfo.com
Code Example: cb1 = new Checkbox(); //Default state is "off" (false). cb1.setLabel("Checkbox 1"); cb3 = new Checkbox("Checkbox 3"); cb3.setState(true); //Set state to "on" (true). cbg = new CheckboxGroup(); cb4 = new Checkbox("Checkbox 4", cbg, false); //initial state: off (false) cb5 = new Checkbox("Checkbox 5", cbg, false); //initial state: off cb6 = new Checkbox("Checkbox 6", cbg, false); //initial state: off
8.6.4 Choices The Choice class provides a menu-like list of choices, accessed by a distinctive button. The user presses the button to bring up a "menu", and then chooses one of the items.
Code Example: choice = new Choice(); choice.addItem("ichi"); choice.addItem("ni"); choice.addItem("san"); choice.addItem("yon"); choice.addItemListener(this); ... public void itemStateChanged(ItemEvent e) { setLabelText(choice.getSelectedIndex(), choice.getSelectedItem()); } 8.6.5 Lists The
List
class
provides
a
scrollable
area
containing
selectable
text
items.
www.arihantinfo.com
Code Example: //Build lists, which allows multiple selections. spanish = new List(4, true); //prefer 4 items visible spanish.add("uno"); ... spanish.add("siete"); spanish.addActionListener(this); spanish.addItemListener(this); italian = new List(); //Defaults to none visible, only one selectable italian.add("uno"); ... italian.add("sette"); italian.addActionListener(this); italian.addItemListener(this); ... public void actionPerformed(ActionEvent e) { List list= (List) e.getSource(); String language = (list == spanish) ? "Spanish" : "Italian"; output.append("Action event occurred on \"" + list.getSelectedItem() + "\" in " + language + ".\n"); } public void itemStateChanged(ItemEvent e) { List list= (List) e.getItemSelectable(); String language = (list == spanish) ? "Spanish" : "Italian"; int index = ((Integer)(e.getItem())).intValue(); if (e.getStateChange() == ItemEvent.SELECTED) { output.append("Select event occurred on item #" + index + " (\"" + list.getItem(index) + "\") in " + language + "." + newline); } else { //the item was deselected output.append("Deselect event occurred on item #" + index + " (\"" + list.getItem(index) + "\") in " + language + "." + newline); }}
www.arihantinfo.com
8.6.6 ScrollPanes A ScrollPane manages a single child component, displaying as much of the component as space permits. By default, a scroll pane's scrollbars are visible only when they're needed.
Code Example: ScrollPane sp1 = new ScrollPane(); sp1.add(aComponent); Scrollbar parameters: SCROLLBARS_AS_NEEDED
The default value. Show each scrollbar only when it's needed. SCROLLBARS_ALWAYS
Always show scrollbars. SCROLLBARS_NEVER
Never show scrollbars. You might use this option if you don't want the user to directly control what part of the child component is shown. Example: ScrollPane sp2 = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);
8.6.7 TextComponent The TextComponent derived classes, TextArea and TextField, display selectable text and, optionally, allow the user to edit the text.
TextArea and TextField:
www.arihantinfo.com
From TextComponent this classes inherit methods that allow them to set and get the current selection, enable and disable editing, get the currently selected text (or all the text), and set the text. Component | TextComponent | +--------------+ | | TextArea TextField Code Example: //Where instance variables are defined: TextField textField; TextArea textArea; public void init() { textField = new TextField(20); textField.addActionListener(this); textArea = new TextArea(5, 20); textArea.setEditable(false); ...//Add the two components to the panel. } public void actionPerformed(ActionEvent evt) { String text = textField.getText(); textArea.append(text + "\n"); textField.selectAll(); } 8.6.8 Menus The
following
applet
shows
many
of
the
menu
features
you're
likely to
use
Note: •
Menus can exist only in menu bars, and menu bars can be attached only to windows (specifically, to Frames).
www.arihantinfo.com
•
Classes that provide menu functionality do not inherit from Component, since many platforms place severe limits on menu capabilities.
MenuComponent subclasses:
MenuItem Each item in a menu is represented by a MenuItem object. CheckboxMenuItem Each menu item that contains a checkbox is represented by a CheckboxMenuItem object. Menu Each menu is represented by a Menu object. Menu is a subclass of MenuItem so that you can create a submenu by adding one menu to another. Popupmenu Represents a popup menu. MenuBar The MenuBar class represents the platform-dependent notion of a group of menus attached to a window. MenuBars can not be bound to Panels. MenuContainer Interface: To be able to contain a MenuComponent, an object must adhere to the MenuContainer interface (Frame, Menu, and MenuBar classes do). Code Example: public class MenuWindow extends Frame implements ActionListener, ItemListener { ... public MenuWindow() { //Build the menu bar. mb = new MenuBar(); setMenuBar(mb); //Build first menu in the menu bar. m1 = new Menu("Menu 1", true); mb.add(m1); mi1_1 = new MenuItem("Menu Item 1_1"); m1.add(mi1_1); ... //Build help menu. m5 = new Menu("Menu 5"); mb.add(m5); //just setting the help menu doesn't work; must add it mb.setHelpMenu(m5); mi5_1 = new MenuItem("Menu Item 5_1");
www.arihantinfo.com
mi5_1.setShortcut(new MenuShortcut(KeyEvent.VK_5)); m5.add(mi5_1); ... //Build second menu in the menu bar. m2 = new Menu("Menu 2"); mb.add(m2); mi2_1 = new CheckboxMenuItem("Menu Item 2_1"); m2.add(mi2_1); //Build third menu in the menu bar. ... //Register as an ActionListener for all menu items. m1.addActionListener(this); m2.addActionListener(this); m3.addActionListener(this); ... //Register as ItemListener on checkbox menu item. mi2_1.addItemListener(this); } ... public void actionPerformed(ActionEvent e) { output.append("\"" + e.getActionCommand() + "\" action detected in menu labeled \"" + ((MenuItem)(e.getSource())).getLabel() + "\".\n"); } public void itemStateChanged(ItemEvent e) { output.append("Item state change detected on item \"" + e.getItem() + "\" (state is " + ((e.getStateChange() == ItemEvent.SELECTED)? "selected)." : "deselected).") + "\n"); }
8.7 AWT Containers 8.7.1 Frames
The Frame class provides windows for applets and applications. Every application needs at least one Frame Code Example: public class MenuWindow extends Frame { boolean inAnApplet = true; TextArea output; public MenuWindow() {
www.arihantinfo.com
//Calls the Frame constructor and adds components to the window . addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { if (inAnApplet) { dispose(); } else { System.exit(0); } } } ... public static void main(String args[]) { MenuWindow window = new MenuWindow(); window.inAnApplet = false; window.setTitle("MenuWindow Application"); window.setSize(450, 200); window.setVisible(true); } } Other methods provided by Frame: String getTitle() and void setTitle(String)
Returns or sets (respectively) the title of the frame's window. Image getIconImage() and void setIconImage(Image)
Returns or sets (respectively) the image displayed when the window is iconified. MenuBar getMenuBar() and void setMenuBar(MenuBar)
Returns or sets (respectively) the menu bar for this Frame. void remove(MenuComponent)
Removes the specified menu bar from this Frame.
8.7.2 Panels The Panel class is a general-purpose Container subclass. You can use it as-is to hold Components, or you can define a subclass to perform special functionality, such as event handling for the objects the Panel contains. Note: The Applet class is a Panel subclass with special hooks to run in a browser or other applet viewer. Code Examples: Panel p1 = new Panel(); p1.add(new Button("Button 1")); p1.add(new Button("Button 2")); p1.add(new Button("Button 3"));
www.arihantinfo.com
A Panel subclass that draws a frame around its contents.
class FramedArea extends Panel { public FramedArea(CoordinatesDemo controller) { ...//Set the layout manager. //Add any Components this Panel contains... } //Ensure that no Component is placed on top of the frame. //The inset values were determined by trail and error. public Insets getInsets() { return new Insets(4,4,5,5); } //Draw the frame at this Panel's edges. public void paint(Graphics g) { Dimension d = getSize(); Color bg = getBackground(); g.setColor(bg); g.draw3DRect(0, 0, d.width - 1, d.height - 1, true); g.draw3DRect(3, 3, d.width - 7, d.height - 7, false); } } 8.7.3 Dialogs The AWT provides support for dialogs -- windows that are dependent on other windows -with the Dialog class. It provides a useful subclass, FileDialog,that provides dialogs to help the user open and save files.
Code Example: class SimpleDialog extends Dialog implements ActionListener { TextField field; DialogWindow parent;
www.arihantinfo.com
Button setButton; SimpleDialog(Frame dw, String title) { super(dw, title, false); parent = (DialogWindow)dw; ...//Create and add components, such as the set button. //Initialize this dialog to its preferred size. pack(); } public void actionPerformed(ActionEvent event) { Object source= event.getSource(); if ( (source == setButton) | (source == field)) { parent.setText(field.getText()); } field.selectAll(); setVisible(false); } } // Here's the code that brings up the dialog: if (dialog == null) { dialog = new SimpleDialog(this, "A Simple Dialog"); } dialog.setVisible(true);
8.8 Using Adapters to Handle Events
Most AWT listener interfaces contain more than one method. For example, the MouseListener interface: 1. mousePressed, 2. mouseReleased, 3. mouseEntered, 4. mouseExited, 5. mouseClicked. You may want to implement only one or two functions to handle the one or two events of interest, but the XXXListener interface may specify half a dozen methods. The language rules are such that you must implement all the methods in an interface even if you just give them empty bodies. The AWT provides an adapter class for each listener interface with more
www.arihantinfo.com
than one method with null bodies, thus allowing you to override as few methods as you like. For example, the MouseAdapter class implements the MouseListener interface. /* * An example of extending an adapter class instead of * directly implementing a listener interface. */ public class MyClass extends MouseAdapter { ... someObject.addMouseListener(this); ... public void mouseClicked(MouseEvent e) { ...//Event handler implementation goes here... } } Listener w/ adapter
interface
Methods in interface
ActionListener
actionPerformed(ActionEvent)
AdjustmentListener
AdjustmentValueChanged( AdjustmentEvent)
ComponentListener ComponentAdapter
componentHidden(ComponentEvent) componentShown(ComponentEvent) componentMoved(ComponentEvent) componentResized(ComponentEvent)
ContainerListener ContainerAdapter
componentAdded(ContainerEvent) componentRemoved(ContainerEvent)
FocusListener FocusAdapter
focusGained(FocusEvent) focusLost(FocusEvent)
KeyListener KeyAdapter
keyPressed(KeyEvent) keyReleased(KeyEvent) keyTyped(KeyEvent)
MouseListener MouseAdapter
mouseClicked(MouseEvent) mouseEntered(MouseEvent) mouseExited(MouseEvent) mousePressed(MouseEvent) mouseReleased(MouseEvent)
MouseMotionListener MouseMotionAdapter
mouseDragged(MouseEvent) mouseMoved(MouseEvent)
WindowListener WindowAdapter
windowOpened(WindowEvent) windowClosing(WindowEvent) windowClosed(WindowEvent) windowActivated(WindowEvent) windowDeactivated(WindowEvent) windowIconified(WindowEvent) windowDeiconified(WindowEvent)
ItemListener
itemStateChanged(ItemEvent)
www.arihantinfo.com
UNIT 9: JFC AND SWING COMPONENT
9.1Introduction 9.2Difference between AWT and Swing Components 9.3Overview of Jcomponent 9.4All about Controls (JComponents) 9.4.1 JApplet Example 9.4.2 Jframe 9.4.3 Changing the Look and Feel (LAF) 9.4.4 Jlabel 9.4.5 JButton 9.4.6 New Feature in JDK 1.2.2 Only: HTML in Button Label 9.4.7 JtoolTip 9.4.8 JtextField 9.4.9 JcheckBox 9.4.10 Jpanel 9.4.11 JSlider Basics 9.1 Introduction JFC is short for Java Foundation classes, which encompasses a group of features to help people build graphical user interfaces (GUIs). The JFC was first announced at the 1997 JavaOne developer conference, and is defined as containing the following features 1. The swing Components: Include everything from buttons to split panes to tables. 2. Pluggable Look & Feel Support: Gives any program that uses Swing components a potentially wide choice of looks and feels, no matter what platform the program is running on. 3. Accessibility API: Enables assistive technologies such as screen readers and Braille displays to get information from the user interface. 4. Java 2D graphics, text, and images in Java applications and applets. 5. Drag and Drop Support (JDK 1.2 only): Provides the ability to drag and drop between a Java application and a native application. 9.2 Difference between AWT and Swing Components The biggest difference between the AWT components and Swing components is that the Swing components are implemented with absolutely no native code. This means that the Swing components can have more functionality than AWT components, since the Swing components aren’t restricted to the least common denominator – the features that are present on every platform. Having no native code also enables the Swing components to be shipped as an add-on to JDK 1.1, instead of only being part of JDK1.2. Even the simplest Swing components have capabilities far beyond what the AWT components offer. For example: • Swing buttons and labels can display images instead of or in addition to text. • You can easily add or change the borders drawn around most Swing components.
www.arihantinfo.com
For example, it’s easy to put a box around the outside of a container or label. • You can easily change the behavior or appearance of a Swing component by either invoking methods on it or creating a subclass of it. • Swing components don’t have to be rectangular. For example, buttons can be round. • Assistive technologies such as screen readers can easily get information from Swing components. For example, a tool can easily get the text that’s displayed on a button or label. Another interesting Swing feature is that you can specify which look and feel your program’s GUI uses. One of the standard look-and-feel options is a cross platform look and feel, the java Look & Feel. By contrast, AWT components always have the look and feel of the native platform. Yet another interesting feature is that Swing components with state use models to keep the state. For example, a JSider uses a BounedRangeModel object to hold its current value and range of legal values. Models are set up automatically, so you don’t have to deal with them unless you want to take advantage of the power they can give you. When you convert AWT programs to Swing, you need to be aware of a few things: • Programs should not, as a rule, use “heavyweight” components alongside Swing components (such as Menu and ScrollPane) and all components that inherit from the AWT Canvas and Panel classes. This restriction exists because when Swing components (and all other “lightweight” components) overlap with heavyweight components, the heavyweight component is always drawn on top. • Swing components aren’t thread safe. If you modify a visible Swing component invoking its setText method, for example – form anywhere but an event handler, then you need to take special steps to make the modification execute on the event dispatching thread. This isn’t an issue for many Swing programs, since component – modifying code is typically in event handlers. • The containment hierarchy for any window or applet that contains Swing components must have a Swing top-level container at the root of the hierarchy. For example, a main window should be implemented as a Jframe instance instead of as a Frame instance. • You don’t add components directly to a top- level container such as a JFrame. Instead, you add components to a container (called the content pane) that is itself contained by the JFrame. 9.3 Overview of JComponent There is an abstract class called JComponent, which is the parent class for most things that can appear on screen. The basic ingredients of a GUI are all subclasses of the class called JComponent. JComponent is the super class that holds the common information about an on-screen control and provides higher level features common to each control, such as: • Size (preferred, minimize, maximum). • Double buffering (a technique to make frequently changing components look smoother with less flickering). • Support for accessibility and internationalization. • Tooltips (pop-up help when you linger on a JComponent). • Support for operating the control with the keyboard instead of the mouse. • Some help for debugging by slowing component rendering so you can see what’s happening.
www.arihantinfo.com
•
The thickness of any lines or insets around the edge of the Control.
The Swing lightweight controls can be divided up as shown in Table GUI Category Basic Controls
Uneditable Display Editable Display
Space-Saving Containers Top-Level Containers Other Containers
Control Button Combo box List Menu Slider Toolbar TextField Label Tooltip Progress bar Table Text Tree Color chooser File chooser Scroll pane Split pane Tabbed pane Frame Applet Dialog Panel Internal Frame Layered pane Root pane
Swing Class Name JButton, JCheckBox, JRadioButton JComboBox JList JMenu, JMenuBar, JMenuItem JSlider JToolbar JTextField, JPasswordField, JTextArea JLabel JToolTip JProgressBar JTable JTextPane, JTextArea, JEditorPane JTree JColorChooser JFileChooser JScrollPane, JScrollBar JSplitPane JTabbedPane JFrame JApplet JDialog, JOptionPane JPanel JInternalFrame JLayeredPane JRootPane
9.4 All about Controls (JComponents) All swing components are the subclasses of the general class JComponent. These classes are the controls or the building blocks from which you create your GUI. What you do with all these components in the following: 1. Add them to the content pane of a container (often JFrame or the JApplet) with a call like: Container pane = MyJContainter.getContentPane (); pane.add (myJComponent); Or, in a single line as: MyJContainer.getContentPane (). add (myJComponent); 2. Register your event-handler using the addSomeListener() method of the component. This tells the window system which routine of yours should be called when the user presses buttons or otherwise makes selections to process the event.
www.arihantinfo.com
Java.lang.Object Java.awt.Compon ent Java.awt.Containe r Javax.swing.JCompone nt (abstract) AbstractButton (abstract)
Javax.swing. JtextComponent (abstact) JLabel
JMenuItem
JMenu
JToggleButto n
JRadioButto n
JButton
JCheckBox
JEditorPane JTextField JTextArea
JPanel JToolTip JOptionPane
JScrollPane
How to Display Components Containers are the objects that are displayed directly on the screen. Controls must be added to a container if you want to see them. The container in this example driver program is called JFrame. JFrame will be the main window of most of your swing applications. Lets create a JFrame, set its size, set it visible, tell it how to arrange JComponents that are added, and add some event-handler code to exit the program when it detects that you have
www.arihantinfo.com
clicked on the JFrame to close it. We’ll split them off into a separate method. Make everything static. In this way, we can use it from the main() method, and we get the following. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class demo { static JFrame jframe = new JFrame (“example”); public static void setupJFrame() { jframe.setSize (400,100); jframe.setVisible (true); jframe.getContentPane ().setLayout (new FlowLayout ()); WindowListener l = new WindowAdapter () { public void windowClosing (WindowEvent e) { System.exit (0);} }; jframe.addWindowListener (l); } public static void main(String[] args) { setupJFrame (); Jbutton jb = new Jbutton(“Press Me”); Jframe.getContentPane ().add(jb); }} The JButton Component that we are trying to demonstrate is printed in bold type. The line that follows add the JComponents to the JFrame’s content pane. To cut down on the extraneous codes in the pages ahead, I’ll show only the statement directly deal with JComponent. That means I’ll show only the two bold statements in the example above. You should supply all the missing code when you compile and run the examples.
9.4.1 JApplet Example This simple example shows the steps required to get what you would have in the AWT if you had a simple applet whose init method did nothing but drop three buttons into the window. Most usage is the same as with Applet •
JApplet inherits from Applet
•
init, start, stop, etc. unchanged
Main differences in use
Components go in the "content pane", not directly in the frame. Changing other properties (layout manager, background color, etc.) also apply to the content pane. Access content pane via getContentPane, or if you want to replace it with your container (e.g. a JPanel), use setContentPane.
www.arihantinfo.com
Default layout manager is BorderLayout (like Frame and JFrame), not FlowLayout (like Applet). This is really the layout manager of the content pane.
You get Java (Metal) look by default, so you have to explicitly switch if you want native look.
Do drawing in paintComponent, not paint.
Double buffering turned on by default.
JAppletExample.java import java.awt.*; import javax.swing.*; public class JAppletExample extends JApplet { public void init() { Container content = getContentPane(); content.setBackground(Color.white); content.setLayout(new FlowLayout()); content.add(new JButton("Button 1")); content.add(new JButton("Button 2")); content.add(new JButton("Button 3")); } } JApplet Example: Result
9.4.2 JFrame Main differences in use compared to Frame:
Components go in the "content pane", not directly in the frame. Changing other properties (layout manager, background color, etc.) also apply to the content pane. Access content pane via getContentPane, or if you want to replace the content pane with your container (e.g. a JPanel), use setContentPane.
www.arihantinfo.com
JFrames close automatically when you click on the close button (unlike AWT Frames).
However, closing the last JFrame does not result in your program exiting Java. So your "main" JFrame still needs a WindowListener.
You get Java (Metal) look by default, so you have to explicitly switch if you want native look.
JFrame Example: This shows the steps required to imitate what you would get in the AWT if you popped up a simple Frame, set the layout manager to FlowLayout, and dropped three buttons into it. JFrameExample.java import java.awt.*; import javax.swing.*; public class JFrameExample { public static void main(String[] args) { JFrame f = new JFrame("This is a test"); f.setSize(400, 150); Container content = f.getContentPane(); content.setBackground(Color.white); content.setLayout(new FlowLayout()); content.add(new JButton("Button 1")); content.add(new JButton("Button 2")); content.add(new JButton("Button 3")); f.addWindowListener(new ExitListener()); f.setVisible(true); } } ExitListener.java import java.awt.*; import java.awt.event.*; public class ExitListener extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); } } JFrame Example: Result
www.arihantinfo.com
9.4.3 Changing the Look and Feel (LAF) 1. Default is "Java LAF" (or "Metal"), a custom look and feel similar to the Windows look. 2. Motif look available on all platforms. Windows and Mac looks are only available on their native platforms.
It is technically easy to work around this restriction, but it is not currently legal to distribute/use applications that do this.
3. You can change look at runtime.
Sounds cool, but rarely used in real life.
Normal place to set look is in constructor of top-level JFrame (or main), or in init in a JApplet.
4. You can get AWT behavior of using native look.
Call the getSystemLookAndFeelClassName method of UIManager, and pass result to UIManager.setLookAndFeel.
Since setLookAndFeel throws an exception, this is a bit inconvenient, and you might want to make a static method in a utility class called " setNativeLookAndFeel". See example below in WindowUtilities.java.
5. Changing the Look and Feel: Examples Here are some utility functions that set the LAF to native, Java (Metal), and Motif, respectively. Since I think that most users will expect the native LAF, I almost always call setNativeLookAndFeel at the beginning of Swing programs. WindowUtilities.java import javax.swing.*; import java.awt.*; class ExitListener extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); } } /** A few utilities that simplify using windows in Swing. * 1998-99 Marty Hall, http://www.apl.jhu.edu/~hall/java/ */ public class WindowUtilities { /** Tell system to use native look and feel, as in previous * releases. Metal (Java) LAF is the default otherwise. */
www.arihantinfo.com
public static void setNativeLookAndFeel() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { System.out.println("Error setting native LAF: " + e); } } public static void setJavaLookAndFeel() { try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch(Exception e) { System.out.println("Error setting Java LAF: " + e); } } public static void setMotifLookAndFeel() { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); } catch(Exception e) { System.out.println("Error setting Motif LAF: " + e); } } /** A simplified way to see a JPanel or other Container. * Pops up a JFrame with specified Container as the content pane. */ public static JFrame openInJFrame(Container content, int width, int height, String title, Color bgColor) { JFrame frame = new JFrame(title); frame.setBackground(bgColor); content.setBackground(bgColor); frame.setSize(width, height); frame.setContentPane(content); frame.addWindowListener(new ExitListener()); frame.setVisible(true); return(frame); } /** Uses Color.white as the background color. */ public static JFrame openInJFrame(Container content, int width, int height, String title) { return(openInJFrame(content, width, height, title, Color.white)); }
www.arihantinfo.com
/** Uses Color.white as the background color, and the * name of the Container's class as the JFrame title. */ public static JFrame openInJFrame(Container content, int width, int height) { return(openInJFrame(content, width, height, content.getClass().getName(), Color.white)); } } In order to implement this Look and Feel example what you have to do is to include a single line in your previous examples after creating this WindowUtility and ExitListener classes as given below. JAppletExample.java import java.awt.*; import javax.swing.*; public class JAppletExample extends JApplet { public void init() { WindowUtilities.setNativeLookAndFeel(); Container content = getContentPane(); content.setBackground(Color.white); content.setLayout(new FlowLayout()); content.add(new JButton("Button 1")); content.add(new JButton("Button 2")); content.add(new JButton("Button 3")); } } JFrameExample.java import java.awt.*; import javax.swing.*; public class JFrameExample { public static void main(String[] args) { WindowUtilities.setNativeLookAndFeel(); JFrame f = new JFrame("This is a test"); f.setSize(400, 150); Container content = f.getContentPane(); content.setBackground(Color.white); content.setLayout(new FlowLayout()); content.add(new JButton("Button 1")); content.add(new JButton("Button 2")); content.add(new JButton("Button 3")); f.addWindowListener(new ExitListener()); f.setVisible(true);
www.arihantinfo.com
} } 9.4.4 JLabel JLabel is the simplest JComponent. It is just a string, image, or both that appears on screen. The contents can be left-, right-, or center aligned according to an argument to the constructor. The default is left aligned. JLabel is cheap, fast way to get a picture or text on the screen. The code to create it: // remember, we are only showing relevant statements from main () ImageIcon icon = new ImageIcon(“star.gif”); JLabel j1 = new JLabel(“you are a star”, icon, JLabel.Center); Frame.getContentPane ().add (j1); Frame.pack (); //size the JFrame to fit its contents. Note the way we can bring in an image from a GIF or JPEG file by constructing an ImageIcon with a pathname to a file. Labels do not generate any events in and of themselves. It is possible, however, to get and set the text of a label. You might do that in response to an event from a different component. The constructors for JLabel are : public public public public public
javax.swing. javax.swing. javax.swing. javax.swing. javax.swing.
JLabel JLabel JLabel JLabel JLabel
(java.lang.String); (java.lang.String,int); (java.lang.String,javax.swing.Icon,int); (javax.swing.Icon); (javax.swing.Icon,int);
The int parameter is a constant from the JLabel class specifying left-, right-, or centeralignment in the area where the label is displayed. JLabels are typically used to augment other controls with descriptions or instructions. A JLabel has three major features that Label does not. The first is the ability to display images, usually by supplying an ImageIcon eiher to the constructor or via a call to setIcon. The second new feature is the ability to place borders around the labels. The third new feature, and the one I am focusing on here, is the ability to use HTML to format the label. The idea is that, if the string for the label begins with "", then the string is interpreted as HTML rather than taken literally. This lets you make multi-line labels, labels with mixed colors and fonts, and various other fancy effects. This capability also applies to JButton. Although nice, this capabillity also has several significant limitations: •
It only works in JDK 1.2.2 or later, or in Swing 1.1.1 or later. Since there is no programmatic way to test if this capability is supported, this can cause significant portability problems.
www.arihantinfo.com
•
Label string must begin with "", not "". This is no problem once you know, but if you are unaware this can cause no end of frustration. Sun has promised to fix this in JDK 1.3 (Kestrel).
•
Embedded images are not supported in the HTML. Thus, you have to use setIcon or supply an ImageIcon to the JLabel constructor (as with the third label in the example shown above); the HTML cannot have an IMG tag.
•
JLabel fonts are ignored if HTML is used. If you use HTML, all font control must be performed via the HTML. For example, one would think that the following would result in large, bold Serif text, but it results in small bold SansSerif text instead:
• •
JLabel label = new JLabel("Bold Text"); label.setFont(new Font("Serif", Font.PLAIN, 36)); ... Sun says that this will probably not be fixed until after the first release of JDK 1.3.
•
You must use , not to force a line break. is totally ignored, and in a JLabel or JButton works like does in "real" HTML, starting a new line but not leaving a blank line in between.
•
Other HTML support is spotty. Be sure to test each HTML construct you use. Letting the user enter HTML text at run-time is asking for trouble.
JLabels with HTML: Example import java.awt.*; import javax.swing.*; /** Simple example illustrating the use of JLabel, especially * the ability to use HTML text (Swing 1.1.1 and Java 1.2 and * later only!). * 1999 Marty Hall, http://www.apl.jhu.edu/~hall/java/ */ public class JLabels extends JFrame { public static void main(String[] args) { new JLabels(); } public JLabels() { super("Using HTML in JLabels"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); Container content = getContentPane(); Font font = new Font("Serif", Font.PLAIN, 30); content.setFont(font); String labelText = "Red and " + "Blue Text"; JLabel coloredLabel =
www.arihantinfo.com
new JLabel(labelText, JLabel.CENTER); coloredLabel.setBorder (BorderFactory.createTitledBorder("Mixed Colors")); content.add(coloredLabel, BorderLayout.NORTH); labelText = "Bold and Italic Text"; JLabel boldLabel = new JLabel(labelText, JLabel.CENTER); boldLabel.setBorder (BorderFactory.createTitledBorder("Mixed Fonts")); content.add(boldLabel, BorderLayout.CENTER); labelText = "The Applied Physics Laboratory is a division " + "of the Johns Hopkins University." + "" + "Major JHU divisions include:" + "" + " The Applied Physics Laboratory" + " The Krieger School of Arts and Sciences" + " The Whiting School of Engineering" + " The School of Medicine" + " The School of Public Health" + " The School of Nursing" + " The Peabody Institute" + " The Nitze School of Advanced International Studies" + ""; JLabel fancyLabel = new JLabel(labelText, new ImageIcon("images/JHUAPL.gif"), JLabel.CENTER); fancyLabel.setBorder (BorderFactory.createTitledBorder("Multi-line HTML")); content.add(fancyLabel, BorderLayout.SOUTH); pack(); setVisible(true); } } Note: also requires WindowUtilities.java and ExitListener.java, shown earlier, plus JHUAPL.gif. 9.4.5 JButton Simple uses of JButton are very similar to Button. You create a JButton with a String as a label, and then drop it in a window. Events are normally handled just as with a Button: you attach an ActionListener via the addActionListener method. The code to create it: JButton jb = new JButton (“Press Me”); JFrame.getContentPane ().add(jb); The code to handle events from it:
www.arihantinfo.com
jb.addActionListener ( new ActionListener () { int i =1; public void actionPerfomed(ActionEvent e) { System.out.println (“pressed “ + i++);} }); When you press this button, the event handler will print out the number of times it has been passed. New Features: Icons, Alignment, and Mnemonics The most obvious new feature is the ability to associate images with buttons. Swing introduced a utility class called ImageIcon that lets you very easily specify an image file (jpeg or GIF, including animated GIFs). Many Swing controls allow the inclusion of icons. The simplest way to associate an image with a JButton is to pass the ImageIcon to the constructor, either in place of the text or in addition to it. However, a JButton actually allows seven associated images: 1. the main image (use setIcon to specify it if not supplied in the constructor), 2. the image to use when the button is pressed (setPressedIcon), 3. the image to use when the mouse is over it (setRolloverIcon, but you need to call setRolloverEnabled(true) first), 4. the image to use when the button is selected and enabled (setSelectedIcon), 5. the image to use when the button is disabled (setDisabledIcon), 6. the image to use when it is selected but disabled (setDisabledSelectedIcon), and 7. the image to use when (setRolloverSelectedIcon).
the
mouse
is
over
it
while
it
is
selected
You can also change the alignment of the text or icon in the button (setHorizontalAlignment and setVerticalAlignment; only valid if button is larger than preferred size), and change where the text is relative to the icon (setHorizontalTextPosition, setVerticalTextPosition). You can easily create buttons with images as well, like this: Icon spIcon = new ImageIcon (“spam.jpg”); JButton jb = new JButton (“press here for spam”, splcon); You can add a keyboard accelerator to a button, and you can give it a symbolic for the text string that it displays. This helps with internationalizing the code. You can also easily set keyboard mnemonics via setMnemonic. This results in the specified character being underlined on the button, and also results in ALT-char activating the button.
9.4.6 New Feature in JDK 1.2.2
In JDK 1.2.2 and Swing 1.1.1 (and later), Sun added the ability to use HTML to describe the text in JButtons and JLabels. This lets you easily have multi-line labels, mixed fonts and colors, and other fancy features. www.arihantinfo.com
JButton Example: Source Code Here is an example of four similar buttons: one with plain text, one with just an image, one with both and the default layout (image to the left, text to the right), and one with the image and text positions reversed. JButtons.java import java.awt.*; import javax.swing.*; public class JButtons extends JFrame { public static void main(String[] args) { new JButtons(); } public JButtons() { super("Using JButton"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); Container content = getContentPane(); content.setBackground(Color.white); content.setLayout(new FlowLayout()); JButton button1 = new JButton("Java"); content.add(button1); ImageIcon cup = new ImageIcon("images/cup.gif"); JButton button2 = new JButton(cup); content.add(button2); JButton button3 = new JButton("Java", cup); content.add(button3); JButton button4 = new JButton("Java", cup); button4.setHorizontalTextPosition(SwingConstants.LEFT); content.add(button4); pack(); setVisible(true); } } Note: also requires WindowUtilities.java and ExitListener.java, shown earlier, plus cup.gif.
JButton Example: Result
www.arihantinfo.com
9.4.7 JToolTip This is a text string that acts as a hint or further explanation. You can set it for any JComponent. It appears automatically when the mouse lingers on that component and it disappears when you roll mouse away. ToolTips don’t generate any events, so there is nothing to handle. We’ll add a ToolTip to the JLabel that we showed earlier. The code to create it: JLabel j1 = new JLabel (“You are a star”, icon, JLabel.Center); jl.setToolTipText (“you must practice to be a star!”); Notice that you don’t directly create a JToolTip object. That is done for you behind the scenes. You invoke the set ToolTipText () method of JComponent. 9.4.8 JTextField This is an area of the screen where you can enter a line of text. There are a couple of subclasses : JTextArea (several lines in size) and JPasswordField (which doesn’t echo what you type in). you can set it to be editable or not-editable. The Code to create it: JLabel jl = new JLabel (“Enter your name : ”); JTextField jtf = new JTextField (25); //field is 25 chars wide The code to retrieve user input from it: TextFields generate key events on each keystroke and an ActionEvent when the user presses a carriage return. This makes it convenient to validate individual keystrokes as they are typed (as in, ensuring that a field is wholly numeric) and to retrieve all the text when the user has finished typing. The code to get the text look like this : jft.addActionListener ( new ActionListener ()) { public void actionPerformed (ActionEvent e) { System.out.println ( “you entered:” +e.getActionCommand () );} }); Container c = jframe.getContentPane(); c.add(jl); c.add(jtf); In this example, running the program, typing a name, and hitting carriage return will cause the name to be echoed on the Sytem.out. You should write some code to try implementing a listener for each keystroke. 9.4.9 JCheckBox A CheckBox screen object that represents a Boolean choice: pressed, not pressed, on, or off. Usually some text explains the choice. For example, a “press for fries” JLabel would have a JCheckBox “Button” allowing yes or no. You can also add an icon to the JCheckBox, just the way you can with JButton. The code to create it JCheckBox jck1 = new JCheckBox (“Kannada”); JCheckBox jck2 = new JCheckBox (“Tamil”); JCheckBox jck3 = new JCheckBox (“Telugu”);
www.arihantinfo.com
JCheckBox jck4 = new JCheckBox (“Malayalam”); Container c = jframe.getContentPane (); c.add (jck1); c.add(jck2); //etc. …. The code to retrieve user input from it CheckBox generates bot ActionEvent and ItemEvent every time you change it. This seems to be for backword compatibility with AWT. We already saw the code to handle ActionEvents with button. The code to register an ItemListener looks like this. Jck2.addItemListener (new ItemListener () { // anonymous class public void itemStateChanged (itemEvent e) { if(e.getStateChange () == e.SELECTED) System.out.print(“selected”); else System.out.print (“de-selected”); System.out.print(“Kannada \n”); } }); In this example, running the program and clicking the “Kannada” checkbox will cause the output of selected Kannada in the system console. Handlers in real programs will do more useful actions as necessary like assigning values and creating objects. The ItemEvent contains fields and methods that specify which objects generated the event and whether it was selected or deselected. 9.4.10 JPanel 1. JPanel Basics In the simplest case, you use a JPanel exactly the same way as you would a Panel. Allocate it, drop components in it, then add the JPanel to some Container. However, JPanel also acts as a replacement for Canvas (Everyone expects there to be a Jcanvas replacing Canvas, just as Jbutton replace Button, JFrame replaces Frame, and so on. There is no Jcanvas. The swing version of Panel, Jpanel, does double duty. It replaces both Canvas and Panel.). When using JPanel as a drawing area in lieu of a Canvas, there are two additional
steps you usually need to follow. First, you should set the preferred size via setPreferredSize (recall that a Canvas' preferred size is just its current size, while a Panel and JPanel determine their preferred size from the components they contain). Secondly, you should use paintComponent for drawing, not paint. And since double-buffering is turned on by default, the first thing you normally do in paintComponent is clear the off-screen bitmap via super.paintComponent. E.g.: public void paintComponent(Graphics g) { super.paintComponent(g); ... } Note that if you are using Swing in Java 1.2, you can cast the Graphics object to a Graphics2D object and do all sorts of new stuff added in the Java2D package. New Features: Borders Aside from double buffering, the most obvious new feature is the ability to assign borders to JPanels. Swing gives you seven basic border types: titled, etched, beveled (regular plus a "softer" version), line, matte, compound, and empty. You can also create your own, of
www.arihantinfo.com
course. You assign a Border via the setBorder method, and create the Border either by calling the constructors directly, or more often by using one of the following convenience methods in BorderFactory: createTitledBorder, createEtchedBorder, createBevelBorder, createRaisedBevelBorder, createLoweredBevelBorder, createLineBorder, createMatteBorder, createCompoundBorder, and createEmptyBorder. These factory methods reuse existing Border objects whenever possible. As a convenience, JPanel lets you supply the LayoutManager to the constructor in addition to specifying it later via setLayout as with Panel. JPanel Example: The following example allocates four bordered panels, set up to look like a simple drawing program. The large one at the left uses a LineBorder, while the other three use TitledBorder. JPanels.java import java.awt.*; import javax.swing.*; public class JPanels extends JFrame { public static void main(String[] args) { new JPanels(); } public JPanels() { super("Using JPanels with Borders"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); Container content = getContentPane(); content.setBackground(Color.lightGray); JPanel controlArea = new JPanel(new GridLayout(3, 1)); String[] colors = { "Red", "Green", "Blue", "Black", "White", "Gray" }; controlArea.add(new SixChoicePanel("Color", colors)); String[] thicknesses = { "1", "2", "3", "4", "5", "6" }; controlArea.add(new SixChoicePanel("Line Thickness", thicknesses)); String[] fontSizes = { "10", "12", "14", "18", "24", "36" }; controlArea.add(new SixChoicePanel("Font Size", fontSizes)); content.add(controlArea, BorderLayout.EAST); JPanel drawingArea = new JPanel(); // Preferred height is irrelevant, since using WEST region drawingArea.setPreferredSize(new Dimension(400, 0)); drawingArea.setBorder(BorderFactory.createLineBorder (Color.blue, 2)); drawingArea.setBackground(Color.white); content.add(drawingArea, BorderLayout.WEST); pack(); setVisible(true); } } Note: also requires WindowUtilities.java and ExitListener.java, shown earlier.
www.arihantinfo.com
SixChoicePanel.java import java.awt.*; import javax.swing.*; public class SixChoicePanel extends JPanel { public SixChoicePanel(String title, String[] buttonLabels) { super(new GridLayout(3, 2)); setBackground(Color.lightGray); setBorder(BorderFactory.createTitledBorder(title)); ButtonGroup group = new ButtonGroup(); JRadioButton option; int halfLength = buttonLabels.length/2; // Assumes even length for(int i=0; i
View more...
Comments