Documente Academic
Documente Profesional
Documente Cultură
History
JDK and JRE
Byte Code and JVM (Java Virtual Machine)
Platform Independent
Applications and Applets
Principle of OOPs
First Java Application
History of Java
Java is a General Purpose, Object Oriented Programming Language
developed by Sun Microsystems of USA I 1991. Originally called Oak by
Games Gosling, one of the invention of the language, java was designed
for the development of software for consumer electronic devices like
TVs, VCRs, toasters and such other electronic Machines.This goal had a
strong impact on the development team to make the language simple,
portable and highly reliable. The java team which included Patrick
Naughton discovered that the existing languages like C and C++ had
limitations in terms of both reliability and portability. However, they
modeled their new language Java on C and C++ but removed a number
of features of of C and C++ that were considered as source of problems
and thus made java really simple, reliable,portable and powerful
language.
Java Milestones :
1990 Sun Microsystems decided to develop special software that could be used
to manipulate consumer electronic devices. A team of Sun Microsystems
programmers headed by James Gosling was formed to undertake this
task.
1991 After exploring the possibility of most Object Oriented Programming
Language C++, the team announced a new language named Oak.
1992 The team, known as a Green Project team by Sun, demonstrated the
application of their new language to control a list of home appliances
using a hand-held device with a tiny touch sensitive screen.
1993 The World Wide Web(WWW) appeared on the internet and transformed
the text-based Internet into a Graphical-rich environment. The green
Project team came up with the idea of developing Web Applets(tiny
programs) using the new language that could run on all types of
computers connected to Internet.
1994 The team developed a web browser called Hot Java to locate and run
applet programs on Internet. Hot Java demonstrated the power of the
new language, thus making it instantly popular among the Internet users.
1995 Oak was named Java, due to some legal snags. Java is just a name
and is not an acronym. Many popular companies including Netscape and
Microsoft announce to their support to Java.
1996 Java established itself not only a leader for Internet Programming but also as
a general-purpose, object oriented programming language. Java found its
home.
Features of Java :
The bytecode is the result of compiling a Java program. You can execute this
code on any platform. In other words, due to the bytecode compilation process
and interpretation by a browser, Java programs can be executed on a variety of
hardware and operating systems. The only requirement is that the system
should have a java-enabled Internet browser.The java compiler is written in
Java, and the interpreter is written in C. The Java Interpreter can execute Java
Code directly on any machine on which a Java interpreter has been installed.
Application and Applets
There are two types of programs that can be built in Java Applications and applets.
Applications can be directly executed by a JVM. In fact, Java can be used to develop
programs for all kinds of applications, Hot Java itself is a Java Application program.
Applets are small Java programs developed for Internet Applications. An applet located
on distant computer (Server) can be downloaded via Internet and executed on a local
computer (Client) using a Java enabled browser. We can develop applets for doing
everything from simple animated graphics to complex games and utilities. Since applets
are embedded in an HTML document and run inside a Web Page, creating and running
applets are more complex than creating application. Stand alone program can read and
write files and perform certain operations that applet can not do. An Applet can only run
within a Web Browser. The Web browser includes a JVM that provides an execution
environment for the applet. It is also possible to use a tool called the appletviewer to
run an applet. This utility is included in the Java Development Kit(JDK) and is used to
test applets. In this manner, an applet written by any developer in the world may be
dynamically downloaded from the Web Server and executed on a client PC or
workstation.
Java Program Java Compiler Virtual Machine
Process of Compilation
Java Compiler
Application Type
Applet Type
Java
Java
Enabled
Interpreter
Browser
Output Output
Principal of OOPs
Object Oriented Programming (OOP) attempts to emulate the real world in software systems.
The real world consists of objects, categorized in classes. In Object Oriented Programming,
classes have attributes, represented by data member. The attributes distinguish an object of
the class. Classes have behaviors, which are represented by methods. The methods define
how an object acts or reacts.
Feature of Object Oriented Programming :
Information Encapsulation(Hiding) :- Objects provide the benefit of information hiding.
Electrical writing in a television should not be tempered with, and therefore should be hidden
from the user. Object Oriented programming allows you to encapsulate data that you do not
want users of the object to access. Typically, attributes of a class are encapsulated.
Abstraction :- Abstraction allows us to focus on only those parts of an object that concern
us. Person operating the television does not need to know the intricacies of how it works. The
person just needs to know how to switch it on, change channels, and adjust the volume.All
the details that are unnecessary to users are encapsulated, leaving only a simple interface to
interact with. Providing users with only what they need to know is known as abstraction. i.e.
Abstraction lets us ignore the irrelevant details and concentrate on the essentials.
Inheritance :- Inheritance is the process by which objects of one class acquire the
properties of objects of another class. Inheritance supports the concept of
hierarchical classification. In OOP, the concept of inheritance provides the idea of
reusability. This means that we can add additional features to an existing class
without modifying it. This is possible by deriving a new class from the existing one.
The new class will have the combined features of both the classes.
Polymorphism :- Polymorphism means One Interface, multiple implementations.
Shape
The class Shape defines a method called getArea() that returns the area of a
shape. However, this method is not implemented by that class. Therefore, it is an
abstract method and Shape is an abstract class.
This means that no objects of class Shape can be created. However, the
functionality of that class can be inheritated by its subclass. The various
subclasses of Shape like Ellipse,Rectangle,Triangle do implement the getArea()
method.
First Java Application
Create the File
The first step to create the HelloWorld application is to copy the text from
listing 7.1 into a file called HelloWorld.java using your favorite text editor (by
choosing Windows, NotePad, or SimpleText on the Macintosh). It is very
important to call the file HelloWorld.java, because the compiler expects the
file name to match the class identifier
Listing 7.1 The HelloWorld application.
public class HelloWorld {
public static void main(String args[]){System.out.println("Hello World!!");
}}
Class Declaration
The first line public class HelloWorld declares a class, which is an Object-Oriented
construct. As stated earlier Java is true Object-Oriented language and therefore,
everything must be placed inside a class. Class is a keyword and declares that a
new class definition follows.
Opening Bace
Every class definition in Java begins with an opening brace { and ends with a
matching closing brace }, appearing in the last line in the example.
The main() method
Every java application program must include the main() method. This is starting
point for the interpreter to begin the execution of the program. A Java application
can have any number of classes but only one of them must include a main method
to initiate the execution.
Public : The Keyword public is an access specifier that declares the main method
as unprotected and therefore making it to accessible to all other classes.
Static : The keyword static which declares this method as one that belongs to the
entire Class and not a part of any Objects of the class.
The main must always be declared be declared as static since the interpreter uses
this method before any objects are created.
Void : The type modifier void states that the main method does not return any value.
All parameters to a method are declared inside a pair of parentheses. Here,
String args[] declares a parameter named args, which contains an array of objects
Of the class type String.
The Output Line
The only executable Statement in the program is
System.out.println("Hello World!!");
Since Java is a true Object Oriented Language, every method must be part of an
Object. The println method is a member of the out Object, which is static data
Member of the System class. This line prints
Hello World!!
to the screen. The method println always appends a newline character to the end
of the string.
Compile the Code
To compile the program, you need to first install the JDK. Then, use the program
javac included with the JDK to convert the text in listing 7.1 to code which the
computer can run. To run javac, on a Macintosh drag the source file over the javac
icon. On any other computer, type the line:
javac HelloWorld.java
at a command prompt. The javac program creates a file called HelloWorld.class
from the HelloWorld.java file. Inside this file (HelloWorld.class) is text known as
bytecodes which can be run by the Java interpreter.
Run the Program
Now that you have compiled the program, you can run it by typing at the command
prompt:
java HelloWorld
After you do this, the computer should print to the screen
Hello World!!
That may not seem very interesting, but then it's a simple program. If you don't see
the Hello World!! on the screen, go back and make sure you have typed in the file
exactly as shown in listing 7.1, and make sure that you called the file
HelloWorld.java.
JAVA CONTROLS
Variables and Constants
Arithmetic Operator and Expressions
Type Conversion in Java
Comments in Java(3 Types)
Javas Control Statements
o If
o If-else
o Do-while
o While
o for
o Increment and Decrement Operators
o Escape Sequences Characters
o Relational and Logical Operators
o Ternary Operators
o Switch case
o Break
o Bitwise Operators
o Arrays-Single and Multidimensional
Variables and Constants
Constants : Constants in Java refer to fixed values that do not change during the
execution of a program. Java supports several types of constants given in figure below :
Java Constant
mantissa e exponent
Floating Interface
Integer Character Boolean
Point
Integer Types
Java consists of four integer types: byte, short, int, and long, which are defined as 8-,
16-, 32-, and 64-bit signed values as summarized in Table below :
The Java integer primitive types.
Integer literals can be specified in decimal, hexadecimal, or octal notation. To specify a decimal
value, simply use the number as normal. To indicate that a literal value is a long, you can append
either "L" or "l" to the end of the number. Hexadecimal values are given in base 16 and include
the digits 0-9 and the letters A-F. To specify a hexadecimal value, use 0x followed by the digits
and letters that comprise the value. Similarly, an octal value is identified by a leading 0 symbol.
For examples of specifying integer literals, see Table 3.7.
Table 3.7. Examples of integer literals.
Floating-Point Types
Support for floating-point numbers in Java is provided through two primitive types-float
and double, which are 32- and 64-bit values, respectively.
Similar to integer literals are Java's floating-point literals. Floating-point literals can be specified in
either the familiar decimal notation (for example, 3.1415) or exponential notation (for example, 6.02e23).
To indicate that a literal is to be treated as a single precision float, append either "f" or "F". To indicate that
it is to be treated as a double precision value, append either "d" or "D".
Java includes predefined constants, POSITIVE_INFINITY, NEGATIVE_INFINITY, and
NaN, to represent the infinity and not-a-number values.
The following list shows some valid floating-point literals:
43.3F,3.1415d,-12.123f,6.02e+23f,6.02e23d,6.02e-23f,6.02e23d
short Width;
long Length, Area;
Area = Length * Width;// In the division below, Area will be converted to a double,// and the
result of the calculation will be a double.
Conversions and the Cast Operator :
Normally with implicit conversion, the conversion is so natural that you don't even
notice. Sometimes though it is important to make sure a conversion occurs between two
types. Doing this type of conversion requires an explicit cast, by using the cast operator.
The cast operator consists of a type name within round brackets. It is a unary operator
with high precedence and comes before its operand, the result of which is a variable of
the type specified by the cast, but which has the value of the original object. The
following example shows an example of an explicit cast:
float x = 2.0;
float y = 1.7;
x - ( (int)(x/y) * y)
When x is divided by y in this example, the type of the result is a floating-point number.
However, value of x/y is explicitly converted to type int by the cast operator, resulting in
a 1, not 1.2. So the end result of this equation is that x equals 1.7.
Not all conversions are legal. For instance, boolean values cannot be cast to any other
type, and objects can only be converted to a parent class.
Casting and Converting Integers
The four integer types can be cast to any other type except boolean. However,
casting into a smaller type can result in a loss of data, and a cast to a floating-
point number (float or double) will probably result in the loss of some precision,
unless the integer is a whole power of two (for example, 1, 2, 4, 8...).
Casting and Converting Characters
Characters can be cast in the same way 16-bit (short) integers are cast; that is,
you can cast it to be anything. But, if you cast into a smaller type (byte), you lose
some data. In fact, even if you convert between a character and a short you an
loose some data.
If you are using the Han character set (Chinese, Japanese, or Korean), you can
lose data by casting a char into a short (16-bit integer), because the top bit will
be lost.
Casting and Converting Booleans
There are not any direct ways to cast or convert a Boolean to any other type.
However, if you are intent on getting an integer to have a 0 or 1 value based on
the current value of a Boolean, use an if-else statement, or imitate the following
code:
int j;boolean tf;...j = tf?1:0; // integer j gets 1 if tf is true, and 0 otherwise.
Conversion the other way can be done with zero to be equal to false, and
anything else equal to true as follows:
int j;boolean tf;...tf = (j!=0); // Boolean tf is true if j is not 0, false otherwise.
Comments in Java
Java supports three types of comment delimiters-the traditional /*
and */ of C, the // of C++, and a new variant that starts with /** and
ends with */.
The /* and */ delimiters are used to enclose text that is to be treated as a
comment by the compiler. These delimiters are useful when you want to
designate a lengthy piece of code as a comment, as shown in the
following:
/* This is a comment that will span multiple source code lines. */
The // comment delimiter is borrowed from C++ and is used to indicate that
the rest of the line is to be treated as a comment by the Java compiler.
This type of comment delimiter is particularly useful for adding comments
adjacent to lines of code, as shown in the following:
Date today = new Date(); // create an object with today's date
System.out.println(today); // display the date
Finally, the /** and */ delimiters are new to Java and are used to indicate that the enclosed text
is to be treated as a comment by the compiler, but that the text is also part of the automatic
class documentation that can be generated using JavaDoc
The Java comment delimiters are summarized in Table 3.1.
Table 3.1. Java comment delimiters.
conti return
if If-else switch break
nue
while do for
Selection Statement : These select one of several control flows. There are
three types of selection statement in Java : if,if-else, and switch.
If statement :
The if statement is a powerful decision making statement and is used to control
the flow of execution of statements. It is a two-way decision statement and is
used in conjunction with an expression. The general form is :
If(test expression)
{
Statement-block;
}
Statement-x;
It allows the computer to evaluate the expression first and then, depending on
whether the value of the expression (relation or condition) is true or false. It
transfers the control to a particular statement.
If the statement is true then the Statement block will be executed;otherwise the
statement-block will be skipped and the execution will jump to the statement-x.
It should be remember that when the condition is true both the statement-block
and statement-x are executed in sequence.
Example :
Class Demo {
public static void main(String args[]) {
If(args.length==0)
System.out.println(You must have command line arguments); }}
If-else statement
if(test expression)
{
True-Block Statement(s);
}
Else
{
False-Block statement(s);
}
Statement-x;
If the test expression is true, then the true-block statement(s) executed
immediately following to the if statement, are executed; otherwise the false
statement(s) will be executed, not both.In both the cases, the control is
transferred subsequently to the statement-x.
Nesting of Ifelse Statement
If(test condition1)
{ if(test condition2) {
Statement-1; }
else {
Statement-2; }
}
else {
Statement-3; }
Statement-x;
If the condition-1 is false, the statement-3 will be executed; otherwise it
continues to perform the second test. If the condition-2 is true, the statement-1
will be evaluated;otherwise statement-2 will be evaluated and then control is
transferred to the statement-x.
Switch Statement: The Java switch statement is ideal for testing a single
expression against a series of possible values and executing the code
associated with the matching case statement.
Switch(expression) {
Case value-1:
block-1;
break;
Case value-2:
block-2;
break;
default:
default-block;
break; }
Statement-x;
Iteration Statement : These specify how and when looping will take place. There
are three types of Iteration statements: while, do and for
The for Statement
The first line of a for loop enables you to specify a starting value for a loop
counter, specify the test condition that will exit the loop, and indicate how the loop
counter should be incremented after each pass through the loop. This is definitely
a statement that offers a lot of bang for the buck. The syntax of a Java for
statement is as follows:
for (initialization; testExpression; incremement)
statement
For example, a sample for loop may appear as follows:
int count;
for (count=0; count<100; count++)
System.out.println("Count = " + count);
In this example, the initialization statement of the for loop sets count to 0. The test
expression, count < 100, indicates that the loop should continue as long as count
is less than 100. Finally, the increment statement increments the value of count
by one. As long as the test expression is true, the statement following the for loop
setup will be executed, as follows:
System.out.println("Count = " + count);
Of course, you probably need to do more than one thing inside the loop. This is
as easy to do as using curly braces to indicate the scope of the for loop.
The while Statement
Related to the for loop is the while loop. The syntax for a while loop is as
follows:
while (booleanExpression)
statement
As you can tell from the simplicity of this, the Java while loop does not have
the built-in support for initializing and incrementing variables that its for loop
does. Because of this, you need to be careful to initialize loop counters prior
to the loop and increment them within the body of the while loop. For
example, the following code fragment will display a message five times:
int count = 0;
while (count < 5) {
System.out.println("Count = " + count);
count++;
}
The dowhile Statement
The final looping construct in Java is the dowhile loop. The syntax for a
dowhile loop is as follows:
do {
statement
} while (booleanExpression);
This is similar to a while loop except that a dowhile loop is guaranteed to execute
at least once. It is possible that a while loop may not execute at all depending on
the test expression used in the loop. For example, consider the following method:
public void ShowYears(int year) {
while (year < 2000) {
System.out.println("Year is " + year);
year++;
}
}
This method is passed a year value, then loops over the year displaying a
message as long as the year is less than 2000. If year starts at 1996, then
messages will be displayed for the years 1996, 1997, 1998, and 1999. However,
what happens if year starts at 2010? Because the initial test, year < 2000, will be
false, the while loop will never be entered. Fortunately, a dowhile loop can solve
this problem. Because a dowhile loop performs its expression testing after the
body of the loop has executed for each pass, it will always be executed at least
once. This is a very valid distinction between the two types of loop, but it can also
be a source of potential errors. Whenever you use a dowhile loop, you should be
careful to consider the first pass through the body of the loop.
Jumping
Of course, it is not always easy to write all of your for, while and dowhile loops so
that they are easy to read and yet the loops terminate on exactly the right pass
through the loop. Java makes it easier to jump out of loops and to control other
areas of program flow with its break and continue statements.
The break Statement
Earlier in this chapter, you saw how the break statement is used to exit a switch
statement. In a similar manner, break can be used to exit a loop
As an example of this, consider the following code:
int year = 1909;
while (DidCubsWinTheWorldSeries(year) == false) {
System.out.println("Didn't win in " + year);
if (year >= 3000) {
System.out.println("Time to give up. Go White Sox!");
break;
}
}
System.out.println("Loop exited on year " + year);
This example shows a while loop that will continue to execute until it finds a year
that the Chicago Cubs won the World Series. Because they haven't won since
1908 and the loop counter year starts with 1909, it has a lot of looping to do. For
each year they didn't win, a message is displayed. However, even die-hard
Cubs fans will eventually give up and change allegiances to the Chicago White
Sox. In this example, if the year is 3000 or later, a message is displayed and
then a break is encountered. The break statement will cause program control to
move to the first statement after the end of the while loop. In this case, that will
be the following line:
System.out.println("Loop exited on year " + year);
The continue Statement
Just as a break statement can be used to move program control to immediately
after the end of a loop, the continue statement can be used to force program
control back to the top of a loop
ARRAYS
One Dimensional Array : is a list of variables of the same type that are
accessed through a common name. An Individual variable in the array is
called an array element. Arrays from a convenient way to handle groups of
related data.
To create an array, you need to perform two steps :
1. Declare Array
2. Allocate space for its elements.
General Form for declaring one dimensional array given below :
type varName[];
Here, type is a valid Java data type and varName is the name of the array. Like
int a[];
This creates a variable named a that refers to an integer array. But it does not
actually create storage for the array.
Second approach to allocate space for One Dimensional Array is
varName=new type[size];
Here varName is name of the array, type is a valid Java type, and size
specifies the number of elements in the array. You can see that the new
operator is used to allocate memory for the array.
These two steps combines like
type varName=new type[size];
For example consider this declaration and allocation :
Int ia=new int[10];
Represents the structure of a one-dimensional array,here ia is array variable
name that can hold 10 integer values.
Multidimensional Array :
In addition to one dimensional we can create arrays of two or more
dimensions. In Java, Multidimensional array are implemented as arrays of
arrays. You need to perform two steps to work with multidimensional arrays : 1.
Declare the array and 2. allocate space for its elements.
The General form is given below :
Type varname = new type[size1][size2];
float a[][]=new float[2][2];
Here a is two dimensional array having 2 rows and 2 columns. i.e. size is 4,
we can store 4 elements in that array.
JAVA Classes and Methods
The General Form of a class
Constructor and Method Overloading
The new Operator
Garbage Collection
Finalize method
Command Line Arguments
The System Class
The General Form of Class
A class array contains three types of items : variable,methods, and constructors.
Variable represent its state. Method provide the logic that constitutes the
behavior defined by a class. The variable and methods can be both static and
instance variable. Constructors initialize the state of a new instance of a class.
The Simplified form of a class is :
class clsName {
//instance variable declarations
type1 varName1=value1;
type2 varName2=value2;
..
//constructor
clsName(cparams1) {
// body of constructor
}
clsName(cparamsN) {
//body of constructor
}
//methods
rtype1 mthName(mparams1) {
//body of method
}
..
}
}
The keyword class indicates that a class named clsName is being declared. This
name must follow the Java naming convention for identifiers. The instance
Variables named varName1 through varNameN included using the normal
variable declaration syntax. Each variable must be assigned a type shown as
type1 through typeN and may be initialized to value shown as value1 through
valueN.
Constructors always have the same name as the class. They do not have return
values.
Method named mthName1 through mthNameN can be included. The return type of
the methods are rType1 through rtypeN, and their Optional Parameter lists are
mparams1 through mparamsN.
Constructors
Often an object will require some form of initialization when it is created. To
accommodate this, Java allows you to define constructor for your classes. A
Constructor is a special method that creates and initializes an object of a particular
class. It has the same name as its class and may accept arguments. Constructor
does not have a return type. Instead, a constructor returns a reference to the
object that it creates.
Constructor Overloading
A class may have several constructors. This feature is called constructor
overloading. When constructors are overloaded each is still called by the name of
its class. However it must have a different parameter list. i.e. Signature of each
constructor must differ.
Method Overloading
Like Constructor, method can also be overloaded. This occurs when two or more
methods have the same name but different signature. Recall that the signature of
a method is a combination of its name and the sequence of the parameter types.
Method Overloading allows you to use the same name for a group of methods that
basically have the same purpose. The println() is an good example of this concept.
It has so many Overloaded forms.Each of these accepts one argument of a
different type. Another advantage of method overloading is that it provides an easy
way to handle default parameter values.
The New Operator
Objects are created using the new operator. The new Operator creates an
instance of a class. It is invoked as follows :
clsName obhRef=new clsName(args);
Here, clsName is the name of the class to instantiated. (Instantiated means to
create an instance.) A reference to the new object is assigned to a variable named
objRef. Notice the expression immediately to the right of the keyword new. This is
known as constructor. A constructor creates an instance of the class. It has the
same name as the class and may optionally have an argument list args.
Garbage Collection
Garbage collection is the mechanism that reclaims the memory resources of an
object when it is no longer referenced by a variable. It prevents programming
errors that could otherwise occur by incorrectly deleting or failing to delete
objects. An object becomes eligible for garbage collection when it is no longer
referenced by any Variable. However, the JVM determines exactly when this
task is performed.
finalize method :
Constructor method used to initialize an object when it is declared. This process
is known as initialization. Similarly, Java supports a concept called finalization,
which is just opposite to Initialization. We know that java run-time is an
automatic garbage collecting system. It automatically frees up the memory
resources used by the objects. But objects may hold other non-object resources
such as file descriptors or window system fonts. The garbage collector cannot
free these resources. In order to free these resources we must use a finalizer
method. This is similar to destructor of C++.
The finalizer method is simply finalize() and can be added to any class. Java
calls that method whenever it is about to reclaim the space for that object. The
finalize method should explicitly define the tasks to be performed.
Command Line Arguments
All java application contain a static method named main().This method takes
one argument that is an array of String objects. These objects represent any
arguments that may have been entered by the user on the command line.
The number of command line arguments is obtained via the expression
args.length. This is an int type. The individual arguments are accessed as
arg[0],args[1],args[2], and so forth.
The System Class
The system class defines several attributes relate to the run-time
environment. It has a static variable named out that contains a reference to a
PrintStream object. The print() and println() methods of that object display
their string arguments on the standard output. The static variable err also
holds a reference to PrintStream object. This is the standard error stream.
The static variable in contains a reference to an InputStream object.
PrintStream and InputStream are classes that provide support for I/O.
Another static method of the system class is exit(). It determines the current
application.
Using Classes and Methods
Instance Methods and Variables
Static keyword
Inner Class/Nested Classes
String Class
Math Class
Wrapper Class
Instance Variables and Methods
Each object has its own copy of all the instance variables defined by its class.
Thus an Instance variable relates to an instance (object) of its class. Instance
variable may be declared by using the following form :
type varName1;
Here, the name of the variable is varName1 and the required type is type.
Instance variables are initialized to default values during the creation of an object.
A Instance Method acts upon an object and can be declared, as follows:
rtype mthname(mparams) {
//body of method
}
Here mthName is the name of the method and type is its return type.
Static Variables and Methods
A static variable is shared by all objects of its class and thus relates to the class
itself. A static variable may be declared by using the static keyword as a modifier
as follows:
static type varName1;
Here the name of the variable ios varName1 and its type is type.
Static variables are initialized to default values when the class loaded into the
memory.
A static method may be declared by using the static keyword as a modifier. A
static method acts relative to a class. It deos not act on specific objects of its
class. To declare a static method as :
static rtype mthName(mparams) {
//body of method
}
}
Here mthName is the name of the method and rtype is its return type an
optional list of parameter types shown as mparams may be specified.
String Class
Strings are class instantiated object and implemented using String Class.
String class expressed as :
String stringName=new String(string);
A string class defines a number of methods that allows you to accomplish a
variety of string manipulation tasks like compareTo() method used to sort an
array of strings in alphabetical order.
Math Class
Mathematical functions such as cos,sqrt, log etc. are frequently used to
analysis of real-life problems. Java supports these basic functions through
Math class defined in the java.lang package.The math function used as follows
Math.function_name();
Like double y=Math.sqrt(x);
Wrapper Class
There are wrapper classes for each of the eight simple types defined by Java.
These are Boolean, Character, Byte,Integer,Float,Long,Short and Double.
They encapsulate boolean,char,byte,int,float,long,short and double values.The
Benefit of using wrapper classes is that they provide methods to convert
strings to simple types. This is a very useful because it gives us a mechanism
by which to process user input.
Inheritance
Fig 3.5
Call By Value and Call By Reference (Argument Passing)
All methods are passed by value. This means that copies of the arguments are
provided to a method. Any changes to those copies are not visible outside
method.
The situation when an array of objects are passed as an argument. In this case
the entire array or object is not actually copied.Instead, only a copy of the
reference is provided. Therefore any changes to the array or object are visible
outside the method. However the reference itself is passed by value.
Overriding Member Methods
When you create a subclass, you inherit all of the functionality of its superclass,
and then you can add or change this functionality as desired. As an example of
this, consider the altered declaration of a Car class in the following code:
public class Car {
private int year;
private float originalPrice;
// calculate the sale price of a car based on its cost
public double CalculateSalePrice() {
double salePrice;
if (year > 1994)
salePrice = originalPrice * 0.75;
else if (year > 1990)
salePrice = originalPrice * 0.50;
else
salePrice = originalPrice * 0.25;
return salePrice;
}
// a public constructor
public Car(int year, float originalPrice) {
this.year = year;
this.originalPrice = originalPrice;
}
}
In this case, the variables like this.year refer to the instance variables, whereas
the unqualified variables like year refer to the constructor's parameters.
The super Variable
In the preceding declaration for ClassicCar, you may have noticed that the
constructor made use of a variable named super. Just as each object has a this
variable that references itself, each object (other than those of type Object itself)
has a super variable that represents the parent class. In this case, super(year,
originalPrice) invokes the constructor of the superclass Car.
Use of Super
Sometimes we may like to prevent a class being further subclassed for security
reasons. A class that can not be subclassed is called a final class. This is
achieved in Java using the keyword final as follows:
Final class AClass ( .)
Any attempt to inherit these classes will cause an error and the compiler will not
allow it.
STRINGS
Strings represent a sequence of characters. The easiest way to represent a sequence
of characters in Java is by using a character array. Example : char charArray[]=new
char[4];
We can declare string using Characters but there is limitation that we can not use
functions related with strings using array like copy of an array is difficult. For that
Java provides String class using objects.
for that two classes are used String and StringBuffer. A Java String is an
instantiated object of the String class.
String stringName;
stringName=new String ("string");
String Array :
String itemArray[]=new String[3];//will create itemArray of size 3 to hold three
string constants.
String Methods :
The String Class defines a number of methods that allow us to accomplish a veriety of string
manipulation tasks.
s2=s1.toLowerCase; //converts the string s1 to all lowercase
s2=s1.toUpperCase; //converts the string s1 to all Uppercase
s2=s1.replace('x','y'); //Replace all occurance of x with y
s2=s1.trim() //Removes the white spaces at the beginning and end of the String s1.
s1.equals(s2) //Returns true if s1 is equal to s2
s1.equalsIgnoreCase(s2) //Returns true if s1=s2, ignoring the case of characters.
s1.length() //Gives the Length of s1
s1.charAt(n) //Gives nth character of s1
s1.compareTo(s2) //Returns negative if s1<s2,positive if s1>s2, and zero if s1 is equal to s2
s1.concat(s2) //concatenates s1 and s2
s1.substring(n) //Gives substring starting from nth character
s1.subsctring(n,m) //Gives substring starting from nth charater upto mth (not including mth)
String.ValueOf(p) //Creates a string object of the parameter p (simple type or object)
p.toString(); //creates a string representation of the object p
s1.indexOf('x') //Gives the position of the first occurence of 'x' in the string s1.
s1.indexOf('x','n') // Gives the position of the 'x' that occurs after nth position in the string s1.
String.valueOf(variable) //Converts the parameter value to string representation.
String Buffer Class :
StringBuffer is a peer class of String. While String creates strings of fixed length, StringBuffer
creates strings of flexible length that can be modified in terms of both length and content. We can
insert characters and substrings in the middle of a string, or append another string to the end.
s1.setCharAt(n,'x')//Modifies the nth character to x
s1.append(s2)//Appends the string s2 to s1 at the end
s1.insert(n,s2)//Inserts the string s2 at the position n of the string s1.
s1.setLength(n)//Sets the length of the string s1 to n. If n<s1.length() s1 is truncated. If n>s1.length()
zeros are added to s1.
Vectors :
Java does not support the concept of variable arguments to a function. This feature can be achieved
in Java through the use of the Vector class contained in the java.util package. This class can be used
to create a generic dynamic array known as vector that can hold objects of any type and any number.
The objects do not have to be homogenious . Arrays can be eaisly implemented as vectors. Vectors
are created like arrays as follows :
Vector intVect = new Vector();//declaring without size
Vector intVect = new Vector(3);//declaring with size
Vectors possess a number of advantages over arrays :
1. It is convenient to use vectors to store objects.
2. A vector can be used to stroe a list of objects that may vary in size.
3. We can add and delete objects from the list as the list as and when required.
A major constraints in using vectors is that we can not directly store simple data types in a vector.
we can only store objects. Therefore, we need to convert simple types to objects. This can be done
using the wrapper classes discussed in the next section.The vector class supports a number of
methods that can be used to manipulate the vectors created.
list.addElement(item)//Adds the item specified to the list at the end
list.elementAt(10)//Gives the name of the 10th object
list.size()//Gives the number of objects present
list.removeElement(item)//Removes the specified item from the list
list.removeElementAt(n)//Removes the item stored in the nth position of the list.
list.removeAllElements()//Removes all the element in the list
list.copyInto(array)//Copies all items from list to array
list.insertElementAt(item,n)//Inserts the item at nth position.
Wrapper Classes
Vectors not handled primitive data types like int,long,char and double. Primitive data types may
be converted object types by using the wrapper classes contained in the java.lang package.
Wrapper class for convering primitive data types are given below
Simple type Wrapper Class
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
The Wrapper classes have number of unique methods for handling primitive data types and
objects.
Converting Primitive Numbers to Object Numbers Using Constructor Methods :
Integer IntVal=new Integer(i);//Primitive integer to Integer Objects here i as primitive data values.
Converting Object Numbers to primitive Numbers using typeValue() method
int i=IntVal.intValue();//Object to primitive integer
Converting Numbers to Strings Using toString() method
str=Integer.toString(i);//Primitive integer to string
Converting String Objects to Numeric Objects using the Static Method valueOf()
IntVal=Integer.valueOf(str);//converts string to Integer objects
Converting Numeric Strings to Primitive Numbers using Parsing Method
int i=Integer.parseInt(str);//converts string to primitive integer.
Input and Output in Java
Files in Java
The Path Name
While dealing with the files, a source of confusion for a beginner in
Java programming is the path name. For example, consider the
following path name on a Unix/Linux machine:
/java/scjp/temp
The first forward slash represents the root directory. This path name
in Windows machines may be written as
C:\java\scjp\temp
Constructors for the File Class
File(String pathname)
Creates an instance of the File class by converting the path name
String to an abstract path name.
An instance of the File class is immutable. This means that once you
have created a File object by providing a path name, the abstract
path name represented by this object will never change.
When you create an instance of the File class, no real file is created
in the file system.
Methods Of File Class:
boolean canRead():
boolean canWrite():
boolean createNewFile():
boolean delete():
boolean exists():
String getAbsolutePath():
String getCanonicalPath():
String getName():
String getParent():
boolean isAbsolute():
boolean isDirectory():
boolean isFile():
String[] list():
String[] listFiles():
boolean mkDir():
boolean mkDirs():
Understanding Streams
Constructors:
FileInputStream(File file)
FileInputStream (String name)
Methods of FileInputStream
int read() throws IOException: Returns the next byte of data, or -1
if the end of the file is reached
void close(): Closes the input stream and releases any system
resources assigned to the stream
The FileOutputStream Class
Methods of FileOutputStream
void write(int b) throws IOException: Writes the passed-in byte to
the stream
void write(byte[] bytes) throws IOException: Writes bytes.length
number of bytes from the passed-in array to the stream
void write(byte[] bytes, int offset, int len) throws IOException:
Writes up to a total of len bytes (starting from offset) from the
passed-in array to the stream
void close(): Closes the output stream and releases any system
resources assigned to the stream
Example code:
1. import java.io.*;
2. public class FileByteCopier {
3. public static void main(String[] args) throws IOException {
4. File inputFile = new File("scjp.txt");
5. File outputFile = new File("scjpcopy.txt");
6. FileInputStream in = new FileInputStream(inputFile);
7. FileOutputStream out = new FileOutputStream(outputFile);
8. int c;
9. while ((c = in.read()) != -1)out.write(c);
10. in.close();
11. out.close();
12. }
13.}
The High-Level Streams
When the unit of information you are interested in is a high-level data
type such as a float, an int, or a String, and you dont want to deal with
bytes directly, you can work with high-level streams.
Two examples of high-level streams are DataInputStream and
DataOutputStream.
DataInputStream class
8. int c;
10. in.close();
11. out.flush();
12. out.close();
13. }
14.}
High-Level Readers and Writers
As you know, you can use DataInputStream and DataOutputStream
to read and write the primitive types in binary format. Similarly, you
can read and write characters in character streams in big chunks
(buffers) and in text format by using the BufferedReader and
BufferedWriter classes, respectively.
BufferedWriter(Writer out);
BufferedWriter(Writer out, int size);
Example Code:
1. import java.io.*;
2. public class FileBufferCopier {
3. public static void main(String[] args) throws IOException {
4. File inputFile = new File("scjp.txt");
5. File outputFile = new File("scjpcopy.txt");
6. BufferedReader in = new BufferedReader(new
FileReader(inputFile));
7. BufferedWriter out = new BufferedWriter(new
FileWriter(outputFile));
8. String line;
9. while ((line = in.readLine()) != null){
10. out.write(line);
11. out.newLine();
12. }
13. in.close();
14. out.close();
15. }
16.}
The PrintWriter Class
The PrintWriter class, a subclass of the Writer class.
The class description of the object, which includes the class name,
the serial version unique ID, a set of flags describing the
serialization method, and a description of the data fields.
Here is a code fragment that reads inthe String and the Date objects
that were written to the file named objectStore.ser in the previous
example:
Static variables are not saved as part of serialization. Recall that the
purpose of serialization is to save the state of an object, and a static
variable belongs to the class and not to an object of the class.
Multithreading
Multitheading is specialized form of multitasking. like windows and other os uses multitasking
technique i.e. they handled more than one process at a time, the same thing we can do in Java
using multithreading technique.
A thread is similar to a program that has a single flow of control. It has a beginning, a body, and
an end,and executes commands sequentially. Java enables us to use multiple flows of control in
developing programs.
Each flow of control is represented by thread that runs parallel to others. i.e. a program that
contains multiple flows of control is known as multithreaded program.Threads in Java are
subprograms of a main application program and share the same memory space, known as
lightweight threads or lightweight process.
Threds running in parallel does not mean that they actually run at the same time. Since all the
threads are running on the same processor, the flow of execution is shared between the threads.
The Java interpreter handles the switching of control between the threads in such a way that it
appears they are running concurrently.
Creating Threads :
Threads are implemented in the form of objects that contain a method called run(). The run()
method
is the heart and soul of any thread.
public void run()
{
....
(statements for implementing threads)
}
The run() method should be invoked by an object of the concerned thread. This can be achieved
by
creating the thread and initiating it with the help of another thread method called start().
A new thread can be created in two ways.
1. By creating a thread class : Define a class that extends Thread class and override its run()
method
with the code required by the thread.
2. By converting a class to a thread :Define a class that implements Runnable interface. The
Runnable
interface has only one method, run(), that is to be defined in the method with the code to be
executed by the thread.
Extending the Thread Class :
We can make our class as runnable as a thread by extending the class java.lang.Thread. This
gives us access
to all the thread methods directly. steps
1. Declare a class as extending the Thread class
2. implement the run() method that is responsible for executing the sequence of code that the
thread will execute.
3. Create a thread object and call the start() method to initiate the thread execution.
Stopping and Blocking a Thread
Stopping a Thread
Whenever we want to stop a thread from running further, we may do so by calling its stop()
method,like
aThread.stop();
This statement causes the thread to move to the dead state. A thread will also move to the dead
state automatically when it reaches the end of its method.
Blocking a Thread
A thread can also be temporarily suspended or blocked from entering into the runnable and
subsequently
running state by using either of the following thread methods:
sleep();//blocked for a specified time
suspend();//blocked until further orders
wait();//blocked until certain condition occurs
These methods causes the thread to go into the blocked (or non- runnable) state.the thread will
return to the runnable state when the specified time is elapsed in the case of sleep(), the resume()
method is invoked in the case of suspend(), and the notify() method is called in the case of wait().
Life Cycle of a Thread
During the life time of a thread, there are many states it can enter. they include :
1. Newborn state
2. Runnabke state
3. Running state
4. Blocked state
5. Dead State
LIFE CYCLE OF A THREAD
New Thread Newborn
stop
start
stop
Running State
Running means that the processor has given its time to the thread for its execution.
The thread runs until it relinquishes control on its own or it is preempted by a higher priority thread. A
running thread may relinquish its control in one of the following situations.
1. It has been suspended using suspend() method. Suspend() can be revived by using the resume()
method.
2. It has made to sleep. We can put a thread a sleep for a specified time period using the method
sleep(time) where time is in milliseconds. This means that the thread is out of the queue during this
time period.
3. It has been told to wait until some event occurs. This is done by using wait() method. The thread can
be scheduled to run again using the notify() method.
Blocked State
A thread is said to be blocked when it is prevented from entering into the runnable state and
subsequently the running state. This happens when the thread is suspended,sleeping, or waiting in order
to satisfy certain requirements. A blocked thread is considered "not runnable" but not dead and therefore
fully qualified to run again.
Dead State
Every thread has a life cycle. A running thread ends its life when it has completed executing its
run() method. It is natural death. However, we can kill it by sending the stop message to it at any
state thus causing a premature death to it.
Thread Priority
In java each thread is assigned a priority, which affects the order in which it is scheduled for
running. The threads that we have discussed so far are of the same priority. The threads of the same
priority are given equal treatment by the java schedular and,therefore,they share the processor on
first-come,fist-serve basis.
JAva permits us to set the priority of a thread using the setPriority() method as follows:
ThreadName.setPriority(intNumber);
the intNumber is an integer value to which the thread's priority is set. The Thread class defines
several priority constants :
MIN_PRIORITY=1
NORM_PRIORITY=5
MAX_PRIORITY=10
intNumber may assume one of these constants or any value between 1 and 10.the default setting is
NORM_PRIORITY.
By assigning priorities to threads, we can ensure that they are given the attention they deserve.
For example, we may need to answer an input as quickly as possible. Whenever multiple threads are
ready for execution, the java system chooses the highest priority thread and executes it. For a thread
of lower priority to gain control, one of the following thing should happen :
1. It stops the running of the run()
2. It is made to sleep using sleep()
3. It is told to wait using wait()
However, If another thread of higher priority comes along, the currently running thread will be
preempted by the incomming thread thus forcing the current thread to move to the runnable state.
Rememberthat the highest priority thread always preempts any lower priority threads.
Syncronization
When multiple threads access shared data then sometimes Data corruption occurs if Multithreaded
programs is not designed correctly that leads to system failure.Unfortunately, such problems can
occur at unpredictable times and be very difficult to reproduce.
As an example, consider A bank account that is shared by multiple customers. Each of these
customers can make deposits to or withdrawals from this account. That application might have a
separate thread to process the actions of each user.
Thread Communication
In deadlock you have seen that how thread acquires a lock and does not relinquish it. In Thread
communication threads can communicate with each other. Thread can temporarily release a lock so
other threads can have an opportunity to execute a synchronized method or statement block. That
lock can be acquired again at a later time.
A class objects defines three methods that allow threads to communicate with each other. The
wait() method allows a thread that is executing a synchronized method or statement block on that
object to release the lock and wait for a notification from another thread. It has these three forms :
Void wait() throws InterruptedException
Void wait(long msec) throws InterruptedException
Void wait(long msec,int nsec) throws InterruptedException
The first form causes the current thread to wait indefinitely. The second form causes the thread to
wait for a msec milliseconds. The last form causes the current thread to wait for msec milliseconds
plus nanoseconds.
notify() method allows a thread that is executing a synchronized method or statement block to
notify another thread that is waiting for a lock on this object. If several threads are waiting, only
one of these is selected. The selection criteria are determined by the implementer of the JVM. The
signature is : void notify()
It is important to understand that when a thread executes the notify() or notifyAll() method it does
not relinquish its lock at that moment. This occurs only when it leaves the synchronized method or
statement block.
APPLET
An applet is a program that can be referenced by the html source code of web page. It is
dynamically downloaded from a Web Server to a browser. The applet then executes within the
environment provided by the browser. Alternatively you may use a tool such as the appletviewer
to run it.
It is important to recognize that downloading code from the Internet and executing it on your
computer is inherently dangerous. Therefore, applet do not have the same capabilities as Java
applications. They are restricted to operating within the confines of a sandbox. In other words
code that is untrusted is not allowed to operate outside certain boundaries.
For Example, applets are normally not allowed to read or write to your local disk. This would
obviously be risky because they could accidentally or maliciously destroy any data stored on that
device.Applet can not execute any native code.
An applet may open a socket connection back to the host from which it was downloaded, but not
to any other host. The reason for this restriction can be understood if you imagine a configuration
in which a firewall protects a corporate Intranet from computer hackers. Assume that an
employee has downloaded an applet from internet to an PC or workstation. If that applet is
allowed to open sockets to any machine, it would then have the potential to steal proprietary
information and send back to the hackers machine. This must be prevented. Therefore, an applet
is not allowed to contact any of those private machines.
Difference between Applet and Application
Applet are not full-featured application programs. They are usually written to accomplish a
small task or a component of a task. Since they are usually designed for use on the Internet,
they impose certain limitations and restrictions in their design.
Applet do not use main() method for initiating the execution of the code. Applets, when
loaded, automatically call certain methods of Applet class to start and execute the applet
code.
Unlike stand-alone applications, applet can not be run independently. They are
run from inside a web page using a special feature known as HTML tag.
Applets cannot red from or write to the files in the local computer.
Applets cannot run any program the local computer.
java.awt.Component
java.awt.container
java.awt.Panel
java.applet.Applet
Chain of classes inherited by Applet class
Initialization State : Applet enters the initialization state when it is first loaded. This is achieved by calling
the init() method of Applet Class.The applet is born. We required following at this stage :
Create objects needed by the applet.
Set up initial values
Load images or fonts
Set up colors
The initialization occurs only once in the applets life cycle. To provide any of the behavior we
must override the init() method.
public void init()
{
-----
}
Running State : Applet enters in the running state when the system calls the start() method of
Applet class. This occurs automatically after the applet is initialized. Starting can also occur if the
applet is already in stopped(idle) state. For example, we may leave the web page containing the
applet temporarily to another page and return back to the page. This again starts applet running.
Note that, unlike init() method, the start() method may be called more than once. We may override
the start() method to create a thread to control a thread to control the applet.
Idle or Stopped State: An applet becomes idle when it is stopped from running. Stopping occurs
automatically when we leave the page containing the currently running applet. We can also do so
by calling the stop() method explicitly.If we use a thread to run the applet, then we must use stop()
method to terminate the thread. We can achieve by overriding the stop() method.
Dead State : An applet is said to be dead when it is removed from memory. This occurs
automatically by invoking the destroy() method when we quit the browser. Like Initialization,
destroying stage occurs only once in the applets life cycle.
Display State: Applet moves to the display state whenever it has to perform some output
operations on the screen. This happens immediately after the applet enters into the running state. The
paint() method is called to accomplish this task.
The Graphics Class : A Graphics object encapsulates a set of methods that can perform graphics
output. Specifically it allows you to draw lines,ovals,rectangles, strings, images, characters, and arcs,
Some of the commonly used methods of the Graphics class are summarized below :
Method Description
void drawArc(int x,int y,int w, Draws an arc between degrees0 and degrees1. The center
int h, int degrees0,int degrees1) of the arc is the center of a rectangle with upper-left
corner at coordinates x and y, width w, and height h. Zero
degrees is at position 3pm on a watch. The angle
increases in a counter clockwise direction.
Void drawImage(Image img, Draws the image img so its upper-left corner is at x,y.
int x,int y,ImageObserver io) Updates about the progress of this activity are sent to io.
void drawLine(int x0,int y0,int x1, Draws a line between the points at x0,y0 and x1,y1.
Int y1)
Void drawOval(int x,int y, Draws an oval.
int w,int h)
void drawPolygon(int x[],int y[],int n) Draws a polygons with n corners.
Void drawRect(int x,int y,int w,int h) Draws a rectangle.
Void drawString(String str,int x,int y) Draws str at location x,y.
void fillarc(int x,int y,int w,int h, Fills an arc between degrees0 and degrees1.
Int degrees0,int degrees1)
void fillOval(int x,int y,int w,int h) Fills an Oval
void fillPolygon(int x[],int y[],int n) Fills the polygon with n corners.
Void fillRect(int x,int y,int w,int h) Fills a rectangle with upper-left corner at coordinates
x and y, width w, and height h.
Color getColor() Gets the color of the current object.
Font getFont() Gets the font of the current object
FontMetrics getFontMetrics() Gets the font metrics of the current object.
Using Colors : the java.awt.Color class is used to work with colors. Each instance of this class
represents a particular color. This class has the following three constructors :
Color(int red,int green,int blue)
Color(int rgb)
Color(float r,float g,float b)
Here red,green and blue are int values that range from 0 to 255.
Display Text : Normally drawString() method is used to draw string on the screen well giving
additional capabilities for controlling the appearance and placement of a string in an applet. A font
determines the size and appearance of characters in a string. That resides in java.awt.Font.
The following is one constructs : Font(String name,int style,int ps)
Here name identifies the font like Arial. The style may be bold,italic or plain and the point size of
the font is ps.
To create a Font setFont() method of the Graphics class.
void setFont(Font font)
Here, font is a Font object. After this method is called, any strings that are output via the
drawString() method are displayed with that font. The java.awt.FontMetrics class allows you to get
several metrics about the size of a font. In addition, you may also determine the size of a string that
displayed in that font. These quantities are provided in pixels.
The specific metrics that are available are ascent, descent leading, and height. Characters extend
above and below that line. The number of pixels above the baseline is the ascent. The number of
pixwls between the descent of one line and the ascent of the next line is the leading. The sum of
descent ,ascent and leading is height. The one constructor for this class is :
FontMetrics(Font font)
Here, font indicates the font for which metrics are wanted. Some of commonly methods are given
below all returns the value in pixels.
int charWidth(char c) Returns the width of c
int charWidth(int I) Returns the width if one character in lowest 16 bit of I
int getAscent() Returns the ascent
int getDescent() Returns the descent
int getHeight() Returns the height
int getLeading() Returns the leading
Int stringWidth(String str) Returns width of str
Using Applet Dimension : Using dimension the data can be used to calculate
the arguments that should be passed to the drawing methods of Graphics class.
For example, you can display a circle at the center of an applet. If applet
resized, the circle remains at its center.
The getSize() method is used to determine the size of an applet.
Dimension getSize()
A dimension object encapsulate a height and width. The following are some
constructor
Dimension(Dimension d)
Dimension(int w,int h)
Here d is a Dimension object.The arguments w and h represents the width and
height in pixels. The class has two instance variable width and height in pixels
of type int.
The applets extend the java.applet.Applet class. State and behavior are inherited from
java.awt.Component,java.awt.Container and java.awt.Panel.The abstract Component class represents
many of the different types of elements you can include in a GUI like Buttons,choices,lists and scroll
bars. Because applet is also an Component you can receive and process events from it by using the
same techniques that apply to other user interface element.The abstract Container class is a
component that may contain other components. A concrete subclass of component is Panel.
The applet class extends Panel. It defines the init(), start(), stop() and destroy() methods are used to
manager the applet life cycle.
void destroy() Destroy applets
AppletContxt getAppletContext() Returns the applet context
URL getCodeBase() Returns the code base
URL getDocumentBase() Returns the document base
Image getImage(URL url) Returns an Image object for the Image at url
Image getImage(URL url, Returns an Image object for the Image at url
String imgName)
String getParameter(String str) Returns the value of parameter pName
void init() Initializes this applet
Void showStatus(String str) Displays str on the status line
void start() Starts this applet
void stop() Stops this applet
The AppletContext class : The java.applet.AppletContext interface defines methods that allow an
applet to interact with context for environment) in which it is executing. This context provided by
either a tool such as the appletviewer or a Web Browser.
Applet getApplet Returns the applet named appName
(String appName)
Enumeration getApplets() Returns an enumeration of the applets in the current context
Image getImage(URL url( Returns an Image object for the image ar the url.
Using Images: The getImage() method of the Applet class returns a java.awt.Image object.
Image getImage(Url url)
Image getImage(URL base, String filName)
The first form accepts one argument that is an absolute URL to identify the image resource. The
second form accepts two arguments. Its frst argument is a URL to identify the base location from
where the image file can be downloaded and its second argument is the name of a specific file.
The drawImage() method of the Graphics class contains the downloading of an Image and displyas
subsets of the image data as it is downloaded to a uses machine.
EVENT HANDLING
An Event is an Object that describes some state change in source. The events generated when a
person interacts with an element in a Graphical User Interface like pressing a Button, clicking the
Mouse, Double click on a list Box Entry, or closing a window.
A source generates events. It has three main responsibilities.First, it must provide methods that allow
listeners to register and unregister for notifications about a specific type of event. Second, it must
generate the event. Finally it must send send the event to all registered listeners. The event may be
unicast to a single listener or multicast to several listeners. It is possible for a source to generate
several types of events. In that case, multiple registration/unregistration methods would be provided.
The methods implemented by a source that allow listeners to register and unregister for events
are as follows :
public void addTypeListener(TypeListener el)
public void addTypeListener(TypeListener el) throws TooManyListenersException
public void removeTypeListener(TypeListener el)
Here type is the type of event and el is the event listener. The first form allows several listeners to
register for the same type of event. The second form is provided if only one listener may register to
receive that type of event. The last form allows a listener to unregister for notifications about a
specific type of event.
A listener receives event notifications. It has three main responsibilities. First, it must register to
receive notifications about specific events. It does so by calling the appropriate registration method
of the source. Second, it must implement an interface to receive events of that type. Finally, it must
unregister if it no longer wants to receive those notifications. It does so by calling the appropriate
unregistration method of the source.
It does so by calling the appropriate unregistration method of the source.The delegation event model
is depicted given below :
Event Listener
Listener
Source
Listener
Here, a source multicasts an event to a set of listeners. The listeners implement an interface to
receive notifications about that type of event. Let us consider how the delegation event model applies
to a button in a graphical user interface. This component generates an event when it is pressed. An
object of class java.awt.ActionEvent is created to encapsulate information about the event.
The java.awt.Button class provides the following methods sp listeners may register and unregister to
receive action events :
void addActionListener(ActionListener al)
void removeActionListenr(ActionListener al)
Here al is a reference to the listener object.
Finally, the java.awt.eventActionListener interface must be implemented by a listener. This
defines one method to receive action events as follows :
void actionPerformed(ActionEvent ae)
Here ae is a reference to the action event.
Event Classes :
A set of classes are provided to represent the various types of AWT events given below :
The EventObject class extends Object and is part of java.util.package, its constructor has this form
: EventObject(Object src) Here src is the object that generates the event.
This class has two methods shown here :
Object getSource()
String toString()
getSource method returns the object that generated the event, and the toString() method returns a
string equivalent to the event.
The abstract AWTEvent class extends EventObject and is part of the java.awt.package. All of the
AWT event types are subclasses of AWTEvent.
Object
Event Object
AWTEvent
ComponentEvent TextEvent
ActionEvent
AdjustmentEvent ItemEvent
KeyEvent MouseEvent
One of its constructors has this form :
AWTEvent(Object source,int id)// Here source is the object that generates the event and id
identifies the type of the event.
Two of its method are shown here :
Int getId()// Returns the type of event
String toString()//Returns the string equivalent of the event.
The ComponentEvent class extends AWTEvent. It defines int constants that are used to identify
four type of components events.
COMPONENT_HIDDEN The component was hidden
COMPONENT_MOVED The component was moved
COMPONENT_RESIZEDThe component was resized
COMPONENT_SHOWN the component became visible.
Event Description
ActionEvent A button is pressed, a list item is double clicked, or a menu item is selected.
AdjustmentEvent A scrollbar is manipulated
ComponentEvent A component is hidden,moved,resized or becomes visible.
ContainerEvent A component is added or removed from a container.
FocusEvent A component gains or losses the Keyboard focus.
InputEvent A mouse or key event occurs.
ItemEvent A check box or list item is clicked, a choice selection is made, or a
checkable menu item is selected or deselected.
KeyEvent Input is retrieved from the Keyboard.
MouseEvent The mouse is dragged or moved, clicked, pressed, or released, or a
checkable menu item is selected or deselected.
TextEvent The value of a text area or text field is changed.
WindowEvent A window is activated, closed, deactivated, deiconified, iconified,
opened, or quit.
The MouseMotionListener interface defines two methods to receive mouse events, as follows :
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)//Here me is the MouseEvent object generated by the source.
Components generate mouse events. The appropriate method of all registered listeners is invoked
and the event is passed as an argument to that method.
The mouseClicked() method is called when the mouse is clicked. The mouseEntered() and
mouseExited() methods are called when the mouse enters or exits the applet. mousePressed() and
mouseReleased() methods are called when the mouse pressed or released.
import java.applet.*;import java.awt.*;import java.awt.event.*;
public class MouseEvents extends Applet implements MouseListener {
public void init() { addMouseListener(this); }
public void mouseClicked(MouseEvent me) { setBackground(Color.blue); repaint(); }
public void mouseEntered(MouseEvent me) { setBackground(Color.green); repaint(); }
public void mouseExited(MouseEvent me) { setBackground(Color.red); repaint(); }
public void mousePressed(MouseEvent me) { setBackground(Color.white); repaint(); }
public void mouseReleased(MouseEvent me) { setBackground(Color.yellow); repaint(); } }
Adapter Class : Here you see that MouseListener interface having five methods and in a program
these five methods should declared by a component and it is inconvenient sometime.Adapter
classes make it easy to deal with this situation. An adapter class provides empty implementation of
all methods in a particular listener interface. It can be useful if you want to override only some of
the methods defined by that interface.The adapter classes in the java.awt.event package and the
listener interfaces that are implemented by each.Here in the given below example an instance of
MyMouseAdapter is created and registered to receive mouse events. The MyMouseAdapter class
extends MouseAdapter and overrides the mousePressed() and mouseReleased() methods.
import java.applet.*; import java.awt.*; import java.awt.event.*;
public class MouseAdapterDemo extends Applet {
public void init() { setBackground(Color.green);
addMouseListener(new MyMouseAdapter(this)); } }
class MymouseAdapter extends MouseAdapter {
MouseAdapterDemo mad;
public MyMouseAdapter(MouseAdapterDemo mad) { this.mad=mad; }
public void mousePressed(MouseEvent me) { mad.setBackground(Color.red); mad.rapaint(); }
public void mouseReleased(MouseEvent me) { mad.setBackground(Color.green);
mad.rapaint(); } }
Adapter class Listener Interface
ComponentAdapter Component Listener
ContainerAdapter Container Listener
FocusAdapter Focus Listener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
Inner Classes : An Inner class is defined within the scope of an expression or another class.
Therefore it has to access to the variables and methods in that scope. The init() method of the applet
instantiate the adapter class and registers that object to receive mouse listener events public class.
MouseInnerDemo extends Applet { public void init() {
addMouseListener(new MyMouseAdapter()); }
Class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent me) { ..}}}
Ex: Here MyMouseAdapter class extends MouseAdapterDemo and overrides the mousePressed()
and mouseReleased() methods.
import java.applet.*; import java.awt.*; import java.awt.event.*;
public class MouseInnerDemo extends Applet {
public void init() { setBackground(Color.green); addMouseListener(new MyMouseAdapter()); }
class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent me) { setBackground(Color.red); repaint(); }
public void mouseReleased(MouseEvent me) { setBackground(Color.green); repaint(); } } }
Anonymous Inner Class: An annonymous inner class is an inner class that does not have a name.
The init() method of the applet instantiates an anonymous adapter class and registers that
object to receive mouse listener events. The annonymous inner class extends
MouseAdapter and
provides an implementation of the mousePressed() method.
public class MouseAnonymouseDemo extends Applet {
public void init() { addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) { } } ); } }
Ex :
import java.applet.*;import java.awt.*;import java.awt.event.*;
public class MouseAnonymousDemo extends Applet {
public void init() { setbackground(Color.green);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me ) { setBackgroundColor(Color.red); repaint();
}
Public void mouseReleased(MouseEvent me) {
setBackground(Color.green); } } ); }
AWT
The container class extends Component. Container as a component that can hold reference to a
number of other components. It allows the GUI that nest containers within containers. Each
container has an associate LayoutManager object that determines where to position its components.
The java.awt.package includes several types of layout managers. The abstract Container class
provides only a default constructor. The add() method resides in the container class used to add the
components.
Button
Canvas
Applet
CheckBox
Panel
Container Dialog FileDialog
Window
Object Component Label Frame
List
Scrollbar
Choice
Text Area
Text
TextField
AWT classes that inherit from Java.lang object.
All the classes that control the placement of objects on the screen inherit from the Java.lang
object.class.
The Applet.class inherits from java.awt.Panel,so you can draw directly to an applet.
AWT classes just inherit from Object. In addition, all the interactive elements (except
menus) inherit from Component. The only other very important thing to note is that
because Applet inherits from Panel (which inherits from Container), applets can
directly contain other objects such as buttons, canvases, and so on. This section describes
how you can build hierarchies of containers in applets.
Graphics Class
The Graphics class is part of the AWT. It's contained in java.awt.Graphics, and it's
the basic class for everything you'll draw on-screen. Applets have associated Graphics
instances, as do various components such as buttons. Drawing methods, such as
drawLine, work on a Graphics instance, so you'll see many calls in this form in a typical
Java applet:
public void paint(Graphics g) {
g.drawLine(10,10,20,20);
}
The Graphics class uses a standard computer coordinate system with the origin in the
upper- left corner.
All coordinate measurements in Java are done in pixels. The size of items, therefore, in
absolute units such as inches or millimeters, differs on various machines due to differing
pixels/inch values.
You'll find that whenever your program has to draw something, you'll be using Graphics
class methods. The following sections discuss the most useful methods.
The update, paint, and repaint Methods
You'll encounter three key methods over and over again as you work with the various user
interface elements.
repaint
Requests a redraw of an item or an entire interface. It then calls update.
update
Controls what happens when repaint is called; you can override this method.
paint
Determines what's done when any item is redrawn. It's called whenever something needs to
be redrawn-for example, when a window is uncovered. All displayable entities have paint
methods that they inherit from Component.
An example of paint and repaint.
import java.awt.*;
import java.applet.Applet;
public class paint_methods extends Applet{
int y;
public void init() {
y = 1;
}
public void start () {
while(true) {
y += 1;
repaint();
//wait 50 milliseconds and then call repaint again
try {
Thread.sleep(50);
} catch(InterruptedException e) {}
}
}
public void paint(Graphics g)
{
//draw a string to the screen
g.drawString("Hello, World!", 25, y );
}
}
Component Class-Shared Features of All Active GUI Elements
All the active components (other than menus), such as Button, inherit from the
Component class. The Component methods provide a wide selection of functionality
applicable to any interactive graphical element.
boolean, action(Event e, Object o)
This method usually is overridden. It's called whenever an ACTION_EVENT occurs on a component.
boolean, keyDown(Event e, int key)
This is called when a KEY_PRESS or KEY_ACTION event reaches a component. The key parameter
specifies which key was involved. You can use this to have components respond to key clicks.
boolean, keyUp(Event e, int key)
This method is invoked when the component receives a KEY_RELEASE event.
boolean, lostFocus(Event e, Object o)
This is called when the object receives a LOST_FOCUS event.
boolean, mouseDown(Event e, int x, int y)
This is invoked when the component receives a MOUSE_DOWN event, caused by the user clicking the
mouse inside the component. The x and y coordinates are in the coordinate system of the component,
where 0,0 is in the upper-left corner.
boolean, mouseDrag(Event e, int x, int y)
This is invoked when the user drags the mouse with the mouse button down over the component,
generating a MOUSE_DRAG event.
boolean, mouseEnter(Event e, int x, int y)
This is invoked each time the mouse goes over the component, generating a MOUSE_ENTER event.
boolean, mouseExit(Event e, int x, int y)
This is called when the component receives a MOUSE_EXIT event. The x and y values-which are
expressed in the component's coordinates-represent the first point outside the component's bounding
rectangle that the mouse goes over. Although Component has a large selection of methods, the following
are the ones you'll use most often.
Rectangle, bounds()
Returns the bounding rectangle that contains the component.
int, checkImage(Image img, ImageObserver iobs)
Monitors the status of an image as it's being composed. You can use this to wait to display a component,
such as a Canvas, that uses an image until the image is ready.
Image, createImage(int width, int height)
Creates a new Image of the specified size.
disable()
Disables the component so that the user can't interact with it. (This is a synchronized method.) The AWT
draws a disabled component differently than an enabled one.
enable()
Enables a disabled component. This is a synchronized method.
Color, getBackground()
Returns the color of the background for the component.
Font, getFont()
Returns the current font for the component.
FontMetrics, getFontMetrics()
Gets the FontMetrics, which contains information about the size of text on the current platform, for the
component.
Color, getForeground()
Returns the foreground color-the one that will be used to draw lines, fill shapes, and so on.
Graphics, paint(Graphics g)
Redraws the component when it needs to be redrawn. Unless you want some custom behavior, the
default method ensures that the component is drawn properly.
boolean, prepareImage(Image img, ImageObserver img_obs)
Enables you to get an image ready for display prior to displaying it on the component. Another version
enables you to specify a size for the image so that it can be scaled.
repaint(long time)
Repaints this component by a specified time or cancels the request.
repaint(int x, int y, int width, int height)
Repaints the specified part of the component.
repaint(long time, int x, int y, int width, int height)
Tries to repaint the specified region. If it can't do so before the specified time, it quits.
reshape(int x, int y, int width, int height)
Enables you to specify the position and size of the component. This is a synchronized method.
resize(int width, int height)
Scales the component to fit in the defined bounding rectangle maintaining the same origin. This is the
same as the version below except you specify the width and height separately rather than with a
Dimension object.
resize(Dimension dim)
Scales the component to fit in the defined bounding rectangle maintaining the same origin.
setBackground(Color a_color)
Sets the background color for a component. This is a synchronized method.
setFont(Font a_font)
Specifies the font that will be used for any text drawn in the component. This is a synchronized method.
setForeground(Color a_color)
Sets the color used for drawing lines and filling in shapes. This is a synchronized method.
show()
Makes the component visible if it had been hidden.
Dimension, size()
Returns the height and width of the component.
update(Graphics g)
Erases the contents of the component's graphic area every time it's called.
validate()
Causes the component to see whether it or any of the components it contains is invalid. If any are
invalid, the Layout Manager is called to bring things up-to-date
Containers
The AWT containers contain classes that can contain other elements. Windows, panels, dialog boxes,
frames, and applets are all containers. Whenever you want to display a component such as a button or
pop-up menu, you'll use a container to hold it. The base class for all containers is-surprise! surprise!-the
Container class.
The Container class has a number of methods that make it easy to add and remove components as
well as to control the relative positioning and layout of those components. Containers can contain other
containers, for example, so a window can contain several panels.
Container is an abstract class, and the methods you'll use most often follow.
add(Component a_component)
Adds a component to the container.
add(Component a_component, int pos)
Adds a component at the specified z position. This is a synchronized method. Be warned that the order
of clipping based on relative z position may vary between machines. This problem should be fixed
eventually, though.
insets, insets()
Returns the insetsobject for the container. Insets define the empty space the
Layout Manager reserves around the edge of the container-the minimum
distance from the edge of a component to the edge of the container.
remove(Component a_component)
Removes the component from the container. This is a synchronized method.
setLayout(LayoutManager lm)
Sets the Layout Manager the container will use. If you supply NULL as the argument, no Layout
Manager is used; you can use absolute positioning.
Panels
Applet inherits from this class, so this section examines Panel in detail so that you can understand
how the various demonstration applets work
Panel inherits from Container. It doesn't create its own window because it's used to group
components inside other containers. Panels enable you to group items in a display in a way that might
not be allowed by the available Layout Managers. If you have a number of entries in your interface, for
example, that have a label and a text field, you can define a panel that contains a label and a text field
and add the panel so that the label and the text field always stay together on the same line (which
wouldn't be the case if you added the two items separately). Without the panel, the Layout Manager
could put the label and the text field on different lines. Panels also are useful in Layout Managers in
which only one item is allowed in an area, such as the BorderLayout Manager. By using a panel, you
can put several components in a single BorderLayout area, such as North.
Insets
An inset object defines the amount of empty space around the edge of a panel. The creator method for
insets follows:
Insets, new Insets(int top, int left, int bottom, int right) This defines a new
Insets instance, which defines the boundaries specified by the input arguments
Frame
A frame is a full-fledged, top-level, resizable window with a menu bar. You can
specify the title, an icon, and a cursor. See the "Frames" section for examples.
Windows
This class isn't used very often, but it's a top-level window without borders and a menu bar.
Labels
Labelsare text items that don't really do much. By using a label instead of
drawString, you can use the Layout Managers to control text placement in a
platform- and monitor-independent manner.
The label creators and the most useful methods for the Label class follow:
new Label(String label)
Produces a label with the specified string.
new Label(String label,int positioning)
Produces a label with the string aligned according to the second value, which should be one of the three
constants Label.CENTER, Label.LEFT, or Label.RIGHT. String, getText()
Returns the label string.
setText(String new_label)
Changes the label text
Buttons
Java buttons are just like the buttons in every other GUI. They are text surrounded by a shape, and they
generate an ACTION_EVENT event-the argument is a button's label-after the user clicks them
new Button(String the_button_label)
Creates a button with the specified label.
setLabel(String the_new_label)
Sets the button label to the specified string.
String getLabel()
Returns the current button label as a string.
Checkboxes
Checkboxes are text items with a checkable icon next to them. They're generally used when you want the
user to be able to set several options prior to making a decision. You usually don't do anything when a
checkbox is checked or unchecked, you usually just read the values of the checkboxes when some other
control, such as a button or menu item, is activated. Just in case you do want the code to do something
when a box's state changes, checkboxes generate an ACTION_EVENT with the new Checkbox state as
the argument after the user clicks on them.
Radio buttons look just like checkboxes, but they are grouped and only one radio button in a group can
be checked at any given time. The next section discusses how to implement radio buttons.
new Checkbox()
Creates a new checkbox with no label.
new Checkbox(String the_label)
Creates a new checkbox with a label.
new Checkbox(String the_label, CheckboxGroup null, boolean checked?)
Creates a new checkbox that is labeled and checked. The middle argument is used with
radio buttons.
setLabel(String the_new_label)
Changes the label of a checkbox.
String getLabel()
Returns the current label as a string.
boolean getState()
Gets the current checkbox state (checked = TRUE).
setState(boolean new_state)
Sets the checkbox state.
Radio Buttons
Checkboxes and radio buttons look different. Even though radio buttons are made up of checkboxes,
they're called radio buttons because that's what they're called in most current GUIs. The only functional
difference is that only one of the items in a radio button group can be selected at one time, like the
buttons on your car radio. This is useful when you want your user to select one of a set of options. The
AWT creates a radio button group by associating a CheckboxGroup instance with all the checkboxes in
the group.
Radio buttons have only one creator method:
new Checkbox(String the_label, CheckboxGroup a_group, boolean checked?) This
creates a new Checkbox that is labeled and checked. The middle argument defines which radio button
group the checkbox belongs to.
In order to use radio buttons, you also need to create a new checkbox group. Use this code:
new CheckboxGroup() Because radio buttons are implemented as checkboxes, the methods
described in the "Checkboxes" section are the ones you'll use to get and set information.
Choice Menus
Choice menus-often called pop-up menus-are designed to allow the user to select an option from a
menu and see the value chosen at all times
new Choice()
Creates a new Choice item.
addItem(String the_item_name)
Adds an item to the Choice menu. It can throw a NullPointerException. This is a synchronized
method. int countItems()
Returns the number of items currently in the menu.
String getItem(int menu_item_number)
Returns the text of the specified menu item (item 0 is the first item in the menu).
int getSelectIndex()
Returns the index of the currently selected item (item 0 is the first item in the menu).
String getSelectedItem()
Returns the text of currently selected menu items.
select(int menu_item)
Changes the selection to the specified item. This is a synchronized method, and it can throw
IllegallArgumentException.
select(String menu_item_name)
Selects the menu item for which the name is the specified string.
Scrolling Lists
Scrolling lists display multiple lines of text, and each line corresponds to a selection item. Scroll bars are
displayed if the text is larger than the available space. The user can select one or more of the lines. Your
program can read the user's selections. Lists generate three event types:
ACTION_EVENT: When a list item is double-clicked. The argument is the name of the list item.
LIST_SELECT: When a list item is selected. The argument is the name of the list item selected.
LIST_DESELECT: When a list item is deselected. The argument is the name of the item deselected.
addItem(String item_label)
Adds the specified item to the end of the current list of items in the list. This is a synchronized
method.
addItem(String item_label, int location)
Adds the specified item to the list at the specified location. This is a synchronized method. Remember
that the first item in the list is numbered 0. For example, addItem("a test", 3) puts "a test"
into the fourth position in the list and slides the previous fourth entry and all entries after it down one.
int clear()
Removes all the entries in the list. This is a synchronized method.
int countItems()
Returns the number of items currently in the list.
String getItem(int location)
Returns the label of the list item at the specified location.
int getSelectedIndex()
Throws an ArrayIndexOutofBoundsException if it's invoked on a list where more than one item
is selected. The method returns -1 if no items are selected. This is a synchronized method. int[]
getSelectedIndexes()
Returns an array of the locations of the selected items. This is a synchronized method. It works with a
single selection and with single-selection lists. It returns -1 if no items are selected. String
getSelectedItem()
Returns the location of the currently selected item. This is a synchronized method. A runtime
Exception is thrown if this method is called on a multiple-selection list. For that reason, and the fact
that getSelectedItems will work with a single item, it's best to avoid this method. If no item is
selected, it returns NULL.
The TextComponent Class-Invisible but Useful
This class is abstract, but it's extended by both TextFields and TextAreas. All the methods covered
here are available in both those GUI elements. TextComponent provides the basic tools for finding out
what text is in a Text item (getText), setting the text in an item (setText), and selecting pieces of
text (setSelect). When using TextFields or TextAreas, you won't have to worry about managing
the cursor location, the insertion point (the vertical cursor that tells the user where newly typed text will
be inserted), or the marking of the selected text. All these functions are done for you by the AWT. The
most useful TextComponent methods follow.
String getSelectedText()
Returns the text currently selected in the text item. The text may have been selected by the user or
through the setSelection method.
String getText()
Returns all the text in the text item.
setText(String new_text)
Enables you to set the text in the text item. This replaces all the text in the item. If you want to insert or
append text, you need to use getText, modify the string, and then use setText to put the modified
string back in the text item. Note that TextArea has insert and append methods.
TextField
Text fields are designed to be used to allow the user to input short pieces of text-usually no more than a
few words or a single number. You also can use them to display information to the user, such as a phone
number or the current sum of the costs of the items the user is going to order. Because TextField
extends TextComponent, you can define whether the user can edit the contents of a TextField
TextArea
Text areas are designed to hold large chunks of text, where large is more than one line. TextArea
extends TextComponent by adding a number of additional methods as well as automatic scrolling of
the text.
new TextArea()
Defines a default empty TextArea.
new TextArea(int rows, int columns)
Defines an empty TextArea with the specified number of rows and columns.
new TextArea(String the_contents)
Defines a TextArea that contains the specified string.
new TextArea(String the_contents, int rows, int columns)
Defines a TextArea containing the specified string and with a set number of rows and columns.
appendText(String new_text)
Appends the specified string to the current contents of the TextArea.
int, getColumns()
Returns the current width of the TextArea in columns.
int, getRows()
Returns the current number of rows in a TextArea.
insertText(String the_text, int where_to_add)
Inserts the specified string at the specified location.
replaceText(String new_text, int start, int stop)
Takes the text between start and stop, inclusive, and replaces it with the specified string.
Organizing Your Interface with Layouts
The traditional method for building a GUI has been to position various interface elements, such as
buttons, at specific locations inside a window and then to allow the user to move the windows around.
Java has had to explore new approaches to defining the layout of components because of the diversity
of standards that it has to support. Although the AWT does let you specify the absolute location of
components, it also gives you Layout Managers that let you define the relative placement of
components that will look the same on a wide spectrum of display devices.
Although you can build your own Layout Manager, it's easiest to use one of the Managers that come
with the AWT. In addition, freeware Layout Managers currently are available; these are discussed along
with how to build your own Layout Manager, and more will be arriving in the future.
FlowLayout
This is the default Layout Manager that every panel uses unless you use the setLayout method to
change it. It keeps adding components to the right of the preceding one until it runs out of space; then it
starts with the next row.
GridLayout
GridLayout's simple rule is to allow the user to define the number of rows and columns in the layout.
GridLayout then sticks one item in each grid cell. The cells are all the same size. The size of the cells
is determined by the number of cells and the size of the container.
new GridLayout(int rows, int cols)
Makes a GridLayout with the specified number of rows and columns. new GridLayout(int rows, int
cols, int horizontal_gap, int vertical_gap)
Makes a GridLayout with the specified rows and columns and with the specified empty space around
each component.
GridBagLayout
This is the most powerful, complex, and hard-to-use Layout Manager that comes with the AWT.
Although it gives you the most flexibility, you should plan to spend some time experimenting with its
parameters before you get a layout that you like. The basic principle of GridBagLayout is that you
associate a constraint object, an instance of GridBagConstraints, with each component in the
layout.
The GridBagLayout Manager uses those constraints to determine how to lay out the components on an
invisible grid, where each component can occupy one or more grid cells. The creator methods for
GridBagConstraints take no input parameters; you customize the instance by changing the following
instance variables.
anchor
Specifies how a component is to be aligned if a component is smaller than the allocated space. The
available constants follow: CENTER: Puts the component in the middle of the area.
EAST: Aligns it with the right-middle side.
NORTH: Aligns it with the top-middle.
NORTHEAST: Puts it in the upper-right corner.
NORTHWEST: Puts it in the upper-left corner.
SOUTH: Aligns it with the bottom-middle.
SOUTHEAST: Puts it in the lower-right corner.
SOUTHWEST: Puts it in the lower-left corner.
WEST: Aligns it with the left-middle side.
fill
Determines what happens if the space allotted to a component is larger than its default size. The allowable
values follow:
BOTH: Tells the component to fill the space in both directions.
HORIZONTAL: Tells the component to fill the space in the horizontal direction.
NONE: Leaves the component at its default size.
VERTICAL: Tells the component to fill the space in the vertical direction.
gridheight
Specifies the height of the component in grid cells. The constant REMAINDER specifies that the component
is the last one in the column and therefore should get all the remaining cells.
gridwidth
Specifies the width of the component in grid cells. The constant REMAINDER specifies that the component
is the last one in the row and therefore should get all the cells remaining in the row.
gridx
Specifies the grid position of the left side of a component in the horizontal direction. The constant
RELATIVE specifies the position to the right of the previous component.
gridy
Specifies the grid position of the top of a component in the vertical direction. The constant RELATIVE
specifies the position below the previous component.
insets
Enables you to set an instance of the Insets class that specifies the whitespace reserved around an
object. It provides more flexibility than ipadx and ipady because it allows different whitespace on the left
than on the right and different whitespace on the top than on the bottom of the component.
ipadx
Specifies the amount of padding (empty space) to put on either side of a component. This increases the
effective size of the component.
ipady
Specifies the amount of padding to put above and below the component.
weightx
Specifies how extra horizontal space (space not needed for the default component sizes) is allocated
between components. This is a relative value, normally chosen to be between 0 and 1, and the values of
the components are compared when allocating space. If one component has a weight of .7 and another
has a weight of .2, for example, the one with weight .7 gets more of the extra space than the one with
.2.
weighty
Same as weightx but for the vertical direction.
BorderLayout
The BorderLayout divides the container into five pieces; four form the four borders of the container
and the fifth is the center. You can add one component to each of these five areas. Because the
component can be a panel, you can add more than one interface element, such as a button, to each of
the five areas. BorderLayout makes room for the items in the four border areas (referred to as
North, South, East, and West), and then whatever is left over is assigned to the Center area. This
layout is nice if you want to place scrollbars around a panel, place the scrollbars in the border regions,
use all four scrollbars or just two, and place the panel you want to scroll in the center.
CardLayout
The CardLayout is different from the others because it enables you to create virtual screen real estate
by defining multiple Cards, one of which is visible at any time. Each Card contains a panel that can
contain any number of interface elements, including other panels. If you've ever used HyperCard on the
Mac, you'll be familiar with this Rolodex type of interface. It's also similar to the tabbed dialog boxes
that are the rage in Microsoft products, but Cards lack any built-in way to go from Card to Card; you
have to provide an interface for that.
Images
The developers of Java knew that working with images is a critical part of any modern programming
language with a goal of implementing user interfaces that meet the criteria of users. Because Java is
platform independent, though, it couldn't use any of the platform-specific formats, such as the Mac's
PICT standard. Fortunately, there already are two platform-independent formats: GIF and JPEG.
These formats are especially nice because they are compressed so that transmitting them takes less of
the limited network bandwidth. The AWT supports both these compression formats, but it uses neither of
them internally. Although you can read in GIF and JPEG files, they are converted into images, which are
just bitmaps. All the work you do in Java with images is based on the Image class. For some strange
reason, even though there is a special package for image-manipulation-related classes
(java.awt.image), the Image class itself resides in the top-level java.awt package.
Image is an abstract class designed to support bitmapped images in a platform-independent manner.
Although this class provides just the basics for working with images, it does have several methods you'll
find useful.
Java uses a model of image producers and image consumers. Image producers generate pixels from a
file or Image object, and image consumers use and/or display those pixels. Both ImageConsumer and
ImageProducer are Java interfaces. AWT comes with ImageProducers for reading from local files
and URLs, arrays in memory, and Image objects. It also comes with CropImageFilter,
RGBImageFilter, and PixelGrabber, which implement the ImageConsumer interface.
Windows
The Window class implements a window with no borders and no menu bar. This generally isn't a useful
class on its own, but because Frame and Dialog-which are useful-extend it, it's useful to take a quick
look at Window's methods.
dispose()
This gets rid of the window's peer. When the window is destroyed, you need to call this method. This is a
synchronized method.
Toolkit, getToolkit()
Returns the Toolkit associated with the window.
show()
Displays the window, making it visible and moving it to the front. This is a synchronized method.
toBack()
Moves the window behind all other windows in the application.
toFront()
Moves the window in front of all other windows. User interactions with a window can cause it to generate
the WINDOW_DESTROY, WINDOW_ICONIFY, WINDOW_DEICONIFY, and WINDOW_MOVED events.
Frames
A Frame implements a resizable window that supports a menu bar, cursor, icon, and title.
Frames generate the same events as windows, which they extend: WINDOW_DESTROY,
WINDOW_ICONIFY, WINDOW_DEICONIFY, and WINDOW_MOVED.
The only parameter you can pass to the Frame constructor is a String, which will be the window title.
You generally will create your own class that extends Frame and contains event-handling methods that
override Component methods such as action, mouseDown, and keyDown. When you extend the class,
you can make creator methods with more input parameters. One useful technique when you're using
Frames with applets is to pass the applet, using this-the Java construct that refers to the object in
whose scope the program line is in-to the Frame so that the Frame methods can invoke applet methods
and read/write applet instance variables.
The most useful Frame methods follow.
dispose()
Enables you to free up windowing resources when you're done with a Frame. This is a synchronized
method. int, getCursorType()
Returns the integer constant that defines which cursor currently is displayed.
Image, getIconImage()
Returns the image being used when the window is reduced to an icon.
MenuBar, getMenuBar()
Returns the frame's menu bar.
String, getTitle()
Returns the frame's title.
boolean, isResizable()
Returns TRUE if the frame can be resized. This attribute can be toggled using the setResizable
method. remove(MenuComponent mb)
Removes the menu bar associated with the frame. This is a synchronized method.
setCursor(int cursor_constant)
Sets the current cursor to the one specified by the input argument.
setIconImage(Image icon)
Sets the icon to be used when the frame is reduced to an icon to the input image.
setMenuBar(MenuBar mb)
Sets the menu bar for the frame. This is a synchronized method. setResizable(boolean flag)
Changes the frame size if the input parameter is TRUE. If the input is FALSE, the frame is a fixed size.
setTitle(String new_title)
Sets the window title.
Menus
You can put a menu bar in a frame or window, but not an applet.
All the other menu classes inherit from MenuComponent. MenuComponent is an abstract class, but
you'll use these methods fairly often.
Font, getFont()
Returns the font used for the current item.
setFont(Font a_font)
Sets the font to be used to display the item on which the menu is invoked. The MenuBar class is a
container for a set of menus displayed with a frame. The key MenuBar methods follow.
Menu, add(Menu a_menu)
Adds a menu to the menu bar. The return value is a handle to the added menu. Menus are added left to
right. This is a synchronized method.
int, countMenus()
Returns the number of menus currently in the menu bar.
Menu, getHelpMenu()
Returns the menu that is defined as the Help menu for the menu bar.
Menu, getMenu(int pos)
Returns the menu item at a given location in the menu bar.
remove(int pos)
Removes the menu at the specified position. This is a synchronized method.
remove(MenuComponent menu)
Removes the specified menu from the menu bar. This is a synchronized method.
setHelpMenu(Menu a_menu)
Sets the specified menu to be the Help menu, which always is placed on the right side of the menu bar.
This is a synchronized method. The Menu class implements pull-down menus. There are two
constructor methods and some useful Menu methods.
new Menu(String a_label)
Creates a new menu with the specified label.
new Menu(String a_label, boolean tear_off)
Creates a new menu with the specified label, which can be torn off from the menu bar.
MenuItem, add(MenuItem an_entry)
Adds the specified menu item to the menu. You make hierarchical menus by adding menus to another
menu. This is a synchronized method.
add(String label)
Adds a new entry to the menu.
addSeparator()
Adds a separating line to the menu.
int, countItems()
Returns a count of the number of items in the menu.
MenuItem, getItem(int position)
Returns the menu item at the specified location.
boolean, isTearOff()
Returns TRUE if the menu has tear off enabled.
remove(int position)
Removes the menu item at the specified location. This is a synchronized method.
remove(MenuComponent an_item)
Removes the specified menu item. This is a synchronized method. The MenuItem class implements
the functionality of a single entry in a pull-down menu. When you create one, you have to supply its
label (as a string) as the input parameter. You use the add method to add MenuItems to menus. The
most useful MenuItem methods follow.
disable()
Grays out a menu item and prevents the user from selecting it.
enable()
Enables a menu item so the user can select it.
enable(boolean some_statement)
Enables a menu item if the logical statement evaluates to TRUE.
StringgetLabel()
Returns the item's label.
boolean, isEnabled()
Returns TRUE if the user can select the item.
setLabel(String new_label)
Changes the label of the menu item to the specified string. An ACTION_EVENT is generated whenever
a menu item is selected by the user. The CheckboxMenuItem class extends MenuItem and
implements the functionality of a menu item with an associated checkbox. The two methods of this
class that will come in handy follow.
boolean, getState()
Returns TRUE if the menu item is checked.
setState(boolean new_state)
Sets the state of the menu item.
Dialog
You can build your own dialog boxes using Frames, but the Dialog class enables you to create modal
dialog boxes. A modal dialog box forces the user to deal with the dialog box before doing anything else.
Although this generally isn't a good idea, certain types of actions, such as notifying a user of a problem,
require user input before the program can do anything else.
Dialog boxes are containers, so you can add components to them, but their default Layout Manager is
BorderLayout rather than FlowLayout. User interaction with dialog boxes can generate the
WINDOW_DESTROY, WINDOW_ICONIFY, WINDOW_DEICONIFY, and WINDOW_MOVED events. As with
other window-related classes, you should call the dispose method (inherited from Window) when the
window is destroyed in order to free up window system resources.
The two dialog creator methods follow.