0% found this document useful (0 votes)
29 views6 pages

Java1 2-ScottMarino

Java 1.2-ScottMarino

Uploaded by

allqaadv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views6 pages

Java1 2-ScottMarino

Java 1.2-ScottMarino

Uploaded by

allqaadv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

BarCharts, Inc.

® WORLD’S #1 QUICK REFERENCE SOFTWARE GUIDES

JAVA OVERVIEW DATA TYPES JAVA STATEMENTS


Sun Microsystems designed the Java language, orig- Primitive Types Statements are simple commands that produce an
inally called Oak, to be used on set-top boxes. James The following types are not objects but are built into action. A group of statements within { } is called a
Gosling created Oak as a subset of C++. This language the Java language. Their size and characteristics will stay block statement and can be used anywhere a statement
had to be small enough to exchange information quick- the same no matter what operating system they are on. can be used.
ly between the cable company and the television and • byte. 8 bits in size and is capable of representing Conditionals
diverse enough to be used by more than one cable com- numbers from –128 to 127. It is initialized to 0. A conditional statement is executed when a specific
pany. • short. 16 bits in size and is able to represent numbers condition is met.
Set-top boxes never materialized during Java’s ini- between –32,768 and 32,767. It is initialized to 0. • if. A conditional using a boolean expression. If the
tial development. Sun Microsystems renamed Oak, • int. 32 bits in size and is able to represent numbers expression returns a value of true, the statement is
calling it Java, and made it available for the Internet. between –2,147,482,648 and 2,147,483,647. It is ini- handled.
• if/else. A conditional with an optional statement
Java debuted on the Internet in 1995. tialized to 0. to handle. If the if expression returns a value of
Java differs from other popular languages in three • long. 64 bits in size and is capable of representing false, Java passes the if statement and handles the
important ways: numbers between –9,223,372,036,854,775,808 and else statement.
1. Java files are small, which makes for fast downloads 9,223,372,036,854,775,807. It is initialized to 0. • else if. A nested if statement, replacing the else
from the Internet. statement in an if/else statement. If the if expression
2. Java programs can run on any operating system that Floating-point Number Types returns a value of false, Java passes the if statement
This type represents numbers with a decimal point. and checks the else if statements. The first else if
contains a Java Virtual Machine (JVM). The JVM statement that returns a value of true is handled.
is an interpreter for Java code and can be found bun- • float. Is capable of representing numbers between
1.4E-45 to 3.4E+38. It is initialized to 0.0d. Code Example:
dled in any modern web browser. if (dataType == byte)
3. Java programs running on a modern web browser • double. Is capable of representing numbers between System.out.println(“This is a byte.”);
are restricted to “the Sandbox.” The Sandbox stops 4.9E-324 to 1.7E+308. It is initialized to 0.0d. else if (dataType == short)
System.out.println(“This is a short.”);
applets from taking over the browser’s operating Other Types else if (dataType == int)
environment. • char. Used to represent letters, numbers, punctuation System.out.println(“This is a int”);
Java development requires an Integrated and other symbols using the Unicode system (the first else if (dataType == long)
Development Environment (IDE) and a Compiler to 128 values of which correspond to ASCII values). It System.out.println(“This is a long.”);
convert Java source code to Java byte code. For a free is initialized to \u0000 (requires 2 bytes of storage for
compiler from Sun Microsystems, go to international characters). • switch. Similar to a nested if statement. This
statement compares a test variable with case vari-
http://java.sun.com and download their most recent • boolean. Hold a value of either true or false (both ables. If a match is found, the statements following
version of the Java Development Toolkit (JDK). are Java predefined values). Boolean values have no the case are handled. If no match is found, the state-
Java applets are programs directly incorporated into direct conversion to integer values and are initialized ments following the default are handled. Note: Test
the HTML pages used on the Internet. to false. and values can only be primitive data types that are
castable to int.
Code Example:
switch (String dataType) {
JAVA OPERATORS case ‘b’ :
System.out.println(“This is a byte.”);
Arithmetic Operators ¡ arg – Logical NOT. Reverses the value of the compari- Break;
These operators are used for basic arithmetic in son following the operator. case ‘s’ :
Java. These operators require arguments on either side. System.out.println(“This is a short.”);
Comparison Operators Break;
arg + arg – Addition The following six operators are used to compare infor- case ‘i’ :
arg – arg – Subtraction or to negate a number mation within Java. These operators return a value of true System.out.println(“This is a int.”);
arg * arg – Multiplication or false. Break;
arg / arg – Division arg == arg – Equal default : System.out.println(“This is a long.”);
arg % arg – Modulus (Remainder of division) arg ¡= arg – Not equal }
Logical Operators arg < arg – Less than • else if...
Logical operators are used along with comparison arg > arg – Greater than Code Example:
operators to form a more complex operation. The dif- arg <= arg – Less than or equal to if (dataType == ‘b’)
ference between a logical and a regular (mandatory) arg >= arg – Greater than or equal to System.out.println(“This is a byte.”);
operator is in the amount of comparison Java does to else if (dataType == ‘s’)
Other Operators System.out.println(“This is a short.”);
the combined expression. These operators return a arg << arg – Left-shift else if (dataType == ‘i’)
value of true or false. arg >> arg – Right-shift System.out.println(“This is a int.”);
arg && arg – Logical AND. If both sides of the com- arg >>> arg – Zero-fill right shift else if (dataType == ‘l’)
parison are true, the expression will return a value ~ arg – Bitwise complement System.out.println(“This is a long.”);
of true. If one side of the comparison is false, the (type)thing – Casting
expression will return a false value. If the first com- arg instanceof class – The instance of operator returns a Loops
parison is false, the second comparison will not be A loop statement is repeated until a specific condi-
value of true or false. This operator checks to see if the tion is met.
checked. preceding argument belongs to the following class, or • for. A loop that repeats a specific number of times.
arg & arg – AND. Same as the logical AND, but both any of its subclasses. The start of a for loop has three parts:
sides of the expression are checked no matter what test ? trueOp : falseOp – Tenary (if-then-else) operator. • initialization. The expression that initializes
the outcome. variable++ - Postfix increment. Adding one to the vari- the loop. (e.g., i = 0)
arg || arg – Logical OR. If either comparison is able value after the reference to the variable. • test. A boolean expression that is checked after
true, the expression will return a value of true. If ++variable – Prefix increment. Adding one to the vari- each pass of the loop. Once the expression returns
neither comparison is true, the expression will able value before the reference to the variable. a value of false, the loop stops. (e.g., i < 10)
return a value of false. If the first comparison is • increment. Any expression normally used to
variable- - - Postfix decrement. Deleting one of the vari- increment the initialization expression and bring the
true, the second comparison is never checked. able values after the reference to the variable. test closer to producing a value of false. (e.g., i++)
arg | arg – OR. Same as the logical OR, but both - -variable – Prefix decrement. Deleting one of the vari- Code Example:
sides of the expression are checked no matter what able values before the reference to the variable. for (i = 0; i < dataType.length; i++) {
the outcome. variable = value - Assignment. Assigns a value to a variable. System.out.println(dataType);
arg ˆ arg – XOR. If the two comparisons have oppo- x += y – The shortcut to x = x + y }
site values, the expression returns a value of true. If x -= y – The shortcut to x = x – y
• while. Used to repeat a statement until a particu-
both comparisons are either true or false, the x *= y – The shortcut to x = x * y lar condition is false. The condition is checked
expression returns a value of false. x /= y – The shortcut to x = x / y before looping.
Code Example:
while (i < dataType.length) {
System.out.println(dataType [i]);
LABELS i++;
continue. Ends the current loop iteration and pro- }
breaks out of all loops in the block containing the label.
ceeds with the next iteration. Optional label speci- The following Code Example shows the optional label: • do/while. Used to repeat a statement until a par-
fies loop to be continued. label: ticular condition is false. The condition is checked
break. Ends the current loop or breaks out of a switch after looping.
for (i = 0; i < dataType.length; i++) { Code Example:
statement. (See Java Statements > Conditionals >
Switch) If the loop is a nested loop, the break com- while (I < dataType.length) { do {
mand breaks out to the next highest loop. If the System.out.println(dataType); System.out.println(dataType [i]);
i++;
optional label is supplied, the break command break label; } while (i < dataType.length);

1
CLASSES METHODS VARIABLES
An object is a self-contained element of a Java pro- Methods are groups of related statements in a class of Variables are objects where information can be
gram that represents a related group of features and is objects that perform an action. Methods are indicated by stored while an application is running. Variable defi-
designed to accomplish specific tasks. A class is a a set of parentheses following the word. (e.g., print()) nition is broken into three parts:
template used to create multiple objects with similar Objects talk to each other through the use of methods. A 1. type. Identifies what type of information the vari-
features. A class definition is broken into two parts: method definition is broken into three parts: able will store. The variable can either be a
1. class. A keyword that lets Java know a class is 1. returnType. The data type or class name of the dataType (See Data Types) or a class type.
about to be defined. value returned by the method. Use void if the method 2. variableName. The name of the variable. Must
2. className. The name of the class. does not return a value. start with a letter, an underscore (_), or a dollar sign
This Code Example is a basic class definition: 2. methodName. The name of the method. ($).
class className { 3. parametersList. The set of variable declarations 3. value. The initial value of the variable. It is not
separated by commas between the parentheses. necessary to give a variable an initial value when it
Inheritance is when one class inherits all of the This Code Example is a basic method signature: is defined. If the value is given, the variable is con-
behaviors and attributes of another class. The sending returnType methodName(pList1, pList2) { sidered a literal.
class is the Superclass and the receiving class is the
• Class methods. Applied to the entire class as a This Code Example is a basic variable definition:
subclass. If the class is a subclass, add the extends type variableName = value:
keyword after the className followed by the whole, and not to its instance. A class method does
superClassName. A class can have multiple subclass- not require an instance of the class in order to be • Class variables. Define the attributes of an
es, but only one superclass. All classes inherit from the called. To define a class method, add the static key- entire class of objects and apply to all instances of
Object class. Whenever the class is used, it is called an word before the returnType in the method signature. it. To define a class variable, add the static keyword
instance of a class. The new operator is used to create • Abstract methods. Hold common behaviors and before the type in the variable definition.
instances of a class. attributes of a class that are shared by its subclasses. • Instance variables. Used to define an object’s
className instanceName = new className(); Objects cannot be created from classes that contain attributes. Instance variables are defined outside of
abstract functions. Instead, such classes are used as a block statement.
• Abstract classes. Templates of behaviors that the basis for inherited classes, with abstract functions • Local variables. Used inside a method defini-
other classes are expected to implement. (See being used to specify what to override. Abstract tion or a smaller block of statements. Once the
Methods > Abstract methods) To define an abstract methods can only be defined in abstract classes. To method is finished, the variable ceases to exist.
class, add the abstract keyword before the class define an abstract method, add the abstract keyword • Access control for variables. Used in the
keyword in the class definition. before the returnType in the method signature. same fashion as access control for methods. (See
• Final classes. Cannot be subclassed by another • Access control for methods. Modifiers that Methods > Access control for methods) To define
class. To define a final class, add the final keyword determine which methods are visible to other classes. access control for a variable, add either the public,
before the class keyword in the class definition. Method access control has four levels: private or protected keyword before the type in the
• Class Access control. Similar to method access 1. public. Makes the method available to any class variable definition.
control. (See Methods > Access control for meth- that wants to use it. • Final variables. Used to make a constant vari-
ods) Class access control has two levels: 2. private. Completely hides the method from able, a variable that never changes. Add the static
1. default. If the class is defined without a mod- being used by any other class. keyword so the value can never change. To define a
ifier, it can only be seen by other classes in the 3. protected. Limits the availability of the method final variable, add the final and static keyword
same package. to subclasses of its class and other classes in the before the type in the variable definition.
2. public. Makes the class visible to any class package. • String literals. Consist of a series of characters
inside and outside of the same package. 4. default. Any method declared without a modifi- between quotation marks. This Code Example is an
To define access control for a class, add the public key- er is available to any other class in that package.
word before the class keyword in the class definition. example of a String definition:
To define access control for a method, add either the String companyName = “Quick Study”;
Package public, private or protected keyword before the
Casting
A package is a collection of classes and interfaces. returnType in the method signature.
• Final methods. Cannot be overridden in a sub- Casting variables means changing the variable’s
Classes from packages other than java.lang must be
imported to be used. To add a class to a package, insert class. To define a final method, add the final key- type. There are three types of casting:
1. Primitive type to primitive type. To con-
the following line as the first line in the class code: word before the returnType in the method signature.
vert one primitive type to another primitive type,
package nameOfpackage;
Calling Methods add the new type in parentheses before the value:
To import a class from a specific package into a Calling a method occurs when a method outside of (primitiveType) value;
class, add the following line below the package desig- the current object is requested. The call statement has 2. Instance to instance. To convert one class
nation line in the class code: two parts: instance to another class instance, add the new class
import nameOfpackage.className; 1. objectName. The name of the object where the name in parentheses before the object:
method resides.
Note: If the entire package will be used in the class, put 2. methodName. The name of the method.
(className) object;
an asterisk (*) in place of the className, and the This Code Example is a basic call statement: 3. Primitive type to object. The java.lang pack-
entire package will be imported. objectName.methodName(); age has a class that corresponds to every primitive
Interface type. This is the basic code to convert a primitive
An interface is a collection of abstract methods that type to an object:
indicate a class has behavior in addition to that inherit- SCOPE AND REFERENCE typeClass variableName = new typeClass(value);
ed from its superclass. Most class references are inter- Note: To convert an object to a primitive type, use a
changeable with interface references. Scope
The scope is the part of a program where a piece of designated method such as Integer.parsInt().
To use an existing interface, add the implements key-
word followed by the interfaceName to a class’ definition. information can be used. When the part defining the Arrays
Code Example: scope has completed execution, the variable ceases to Arrays are used to simplify code when there are
class className implements interfaceName { exist. When a variable is defined in Java, it has a spe- multiple variables with the same primitive data type or
cific scope. To make the variable usable by the entire class. Each object in an array goes into its own num-
Declaring an interface follows the same definition program, or global scope, it must be defined alone and bered slot. Array subscripts start with zero (0), so if an
as a class declaration. The only difference is the class outside of a block statement. To limit the variable to one object is the fourth argument in the subscript, its num-
keyword is replaced with the interface keyword. part of the program, or local scope, it must be defined ber is three (3).
Interfaces can exist alone and with no inheritance, not within a block statement. To declare a variable as an array, add a set of brack-
even to the Object class, but cannot be instantiated. • this keyword. Used to refer to the current object ets ([]) after the variableName.
Interfaces can inherit from multiple superclasses. in the current class. Code Example:
Methods declared inside an interface are set to pub- • super keyword. Used to refer to the current int numbers[] = { 1, 2, 3, 4 };
lic and abstract with or without the modifiers added object in a superclass.
to the signature, but do not have bodies, and must be Reference Every object in an array is separated by a comma.
implemented in the class into which the interface is A reference is a type of pointer used to indicate an To access a specified object in an array, refer to its sub-
implemented. Variables declared inside an interface Object’s location. Objects can be passed from one script number.
method to another, from one application to another, or numbers[3] = 8; - Replaces a value of 4.
are set to public, static and final with or without the
modifiers added to the statement. from one applet to another. Once an object is defined in To replace an object in an array, refer to its subscript
one of the above forms, it is passed by reference. number, then assign a new value.
Applications Whatever happens to an object once it has been passed numbers[3] = 8; - Replaces a value of 4 with 8.
Applications need one class which serves as the start- affects the original object. Pass definitions are broken
ing point for the rest of the application. The starting into four parts: An array can be defined in one statement and have
class is designated by the main() method. The following 1. variable. The variable that will hold the value of its subscript filled in another statement. In the defini-
Code Example is a basic main() method signature: the passed object. tion statement, Java must be told how many spaces to
public static void main(String argument[]) { 2. class. The class the object is passed to . hold for that array. The following Code Example cre-
3. method(). The method the object is passed to . ates a string array and holds 5 slots in its subscript,
The String instance, arguments[], is used for pro- 4. passedObject. The object being passed. then fills the first 4 slots with the characters that make
gram arguments. The body of the main() method This Code Example is a basic pass definition: up the words Quick Study Reference Guides:
receives any code required to start the application, such variable = class.method(passedObject); String[] s = new String[5];
as the initialization of variables or the creation of class s[0] = “Quick”;
instances. Note: The only class that needs a main() Java is a close relative to C++. Most of Java s[1] = “Study”;
method is the starting class, and if a main() method is was based on the C++ language. Java methods s[2] = “Reference”;
added to a helper class, it will be ignored. are C++ functions. s[3] = “Guides”;

2
GRAPHICS FONTS
Graphics – import java.awt.Graphics • Acyclic. The color does not repeat. Fonts – import java.awt.font;
The graphics class contains methods for drawing GradientPaint g = new GradientPaint(x1, y1, The font class is used to define different fonts dis-
lines, ovals, circles, arcs, rectangles and polygons. color1, x2, y2, color2, false); played on screen. Java has its own set of fonts built
Before defining a drawing object, create an instance of • Cyclic. The color repeats multiple times. into the compiler. This list shows the relationship
the graphics class. (The standard instance name is GradientPaint g = new GradientPaint(x1, y1, between Java, Macintosh and Windows fonts:
screen.) The following drawing objects are defined color1, x2, y2, color2, true); Java Mac PC
under the screen instance: Courier Courier Courier New
To make the GradientPaint() method instance “g” active, Dialog Geneva MS Sans Serif
• screen.drawLine(x1, y1, x2, y2); - Draws a line use the setPath(instance) method, from the graphics2D
from coordinates x1, y1 to coordinates x2, y2. Helvetica Helvetica Arial
class instance screen2D, in the init() or main() method. Symbol Symbol WingDings
• screen.drawRect(x1, y1, W, H); - Draws and out- Stroke control gives the creator the ability to customize
lines a rectangle at coordinates x1, y1 with a width TimesRoman TimesRoman TimesNewRoman
a stroke’s width, end points and corners. A stroke’s end
of W and a height of H. point can be customized with the following styles: Java 1.1 changes TimesRoman, Helvetic and Courier
• screen.drawRoundRect(x1, y1, W, H, w, h); - • CAP_BUTT – No cap is added to the ends of a stroke.
to serif, sanserif and monospace respectively. Java also
Draws and outlines a rectangle with rounded cor- • CAP_ROUND – A rounded cap is added to both ends
has font styles. The following list shows the style and
ners at coordinates x1, y1 with a width of W and a of a stroke. how it is defined:
height of H. The rounded corners will have a width Style Definition
• CAP_SQUARE – A squared cap is added to the end of
of w and a height of h. Plain Font.PLAIN
a stroke. Bold Font.BOLD
• screen.drawOval(x1, y1, W, H); - Draws and out-
lines an oval at coordinates x1, y1 with a width of W A stroke’s corners can be customized with the follow- Italic Font.ITALIC
and a height of H. ing styles: Bold Italic Font.BOLD + Font.ITALIC
• screen.drawArc(x1, y1, W, H, s, f); - Draws and • JOIN_MITER – The corner of a stroke is pointed. The font name, style and size are defined in one
outlines an arc at coordinates x1, y1 with a width of • JOIN_ROUND – The corner of a stroke is rounded. statement. The following Code Example is a font def-
W and a height of H. The arc will start at the s • JOIN_BEVEL – The corner of a stroke is flattened. inition for font TimesRoman Bold at 36 point:
degree and will curve f degrees. The following Code Example is a stroke definition for a Font f = new Font(“TimesRoman”, Font.BOLD, 36”);
Note: The definitions for rectangle, round rectangle, stroke with a width of 4 pixels and rounded caps and corners: To make the font class instance “f ” active, use the
oval and arc have two methods. The draw method, BasicStroke s = new BasicStroke(4, setFont(instance) method from the graphics class
shown, is used to draw and outline the drawing BasicStroke.CAP_ROUND, instance screen. To display a string on screen using the
object. The fill method is used to draw and fill the BasicStroke.JOIN_ROUND); font class instance “f,” use the drawString(string)
object with the declared drawing color. To fill one method from the graphics class instance screen in the
of the above drawing objects, replace the word draw To make the BasicStroke() method instance “s” init() or main() method.
with fill. active, use the setStroke(instance) method, from the
graphics2D class instance screen2D, in the init() or
Polygons can have any desired number of points, so main() method.
their definition is different from the drawing objects 2D drawing objects take advantage of the anti-alias
COLORS
above. The polygon is not defined under the screen feature (using the setRenderingHint() method). The Color/Colorspace – import java.awt.color;
instance. Instead, use the following Code Example as arguments for drawing objects in 2D are similar to that The color class contains methods used to set the cur-
a basic polygon definition: of the regular graphics class: rent color used in drawing operations, set the back-
int x[] = { x1, x2, x3, x4, x5 . . .}; • Line2D.Float l = new Line2D.Float(x1, y1, x2, y2); ground color of applets and other windows, and set the
int y[] = {y1, y2, y3, y4, y5 . . .}; • Rectangle2D.Float r = new Rectangle2D.Float(x1, foreground color of the user interface objects. The col-
int points = x.length; y1, W, H); orspace class contains standard color-descriptions or
Polygon p = new Polygon(x, y, points); • Ellipse2D.Float e = new Ellipse2D.Float(x1, y1, colorspaces, such as CMYK and RGB. The default
Line 1 and 2 define arrays x and y separately. Line 3 W, H); colorspace is sRGB but can be changed to any color-
defines integer points as the number of values stored in • Arc2D.Float a = new Arc2D.Float(x1, y1, W, H, s, space stored in the colorspace class. The following
array x. Line 4 creates an instance of the Polygon f, Arc2D.OPEN); Code Example is a color definition for black using the
object, defines coordinates x and y, and gives the num- default color-description:
The last argument on this statement is new and has Color c = new Color(0, 0, 0);
ber of points plotted. three options:
• p.addPoint(x, y); - Adds a point to the polygon p. To make the color class instance “c” active, use the
• Arc2D.OPEN – Leaves the arc open at end points s setColor(instance) method from the graphics class
• draw.Polygon(p); - Draws and outlines polygon p. and f.
• fillPolygon(p); - Draws polygon p and fills the poly- instance screen in the init() or main() method. To make
• Arc2D.CHORD – Closes the arc with a straight line the color class instance “c” the background color, use
gon with the declared drawing color. connecting point s and f. the setBackground(instance) method from the graphics
The graphics class has other methods that are • Arc2D.PIE – Closes the arc with two lines extending class instance screen in the init() or main() method. To
extremely useful: separately from end points s and f and meeting at a make the color class instance “c” the foreground color,
• screen.copyArea(x1, y1, W, H, R, D); - Copies the 45º angle. use the setForeground(instance) method from the graph-
area at coordinates x1, y1 with a width of W and a Polygons2D are defined differently than the other 2D ics class instance screen in the init() or main() method.
height of H. The copied area is then pasted R pix- drawing objects. Java has a standard color palette defined by names.
els to the right and D pixels down from the origin. GeneralPath p + new GeneralPath(); The following is a list of all colors found in the stan-
• screen.clearRect(x1, y1, W, H); - Clears the screen dard color palette along with their sRGB arguments:
p.moveTo(x1, y1);
area at coordinates x1, y1 with a width of W and a p.lineTo(x2, y2); Color sRGB Color sRGB
height of H. p.closePath(); black 0, 0, 0 blue 0, 0, 255
Note: To clear the entire screen, replace the width and cyan 0, 255, 255 darkGray 64, 64, 64
height arguments with size().width and Line 1 creates an instance of the GeneralPath() gray 128, 128, 128 green 0, 255, 0
size().height. Java 1.2 replaces the size() method method. Line 2 defines the first point plotted for poly- lightGray 192, 192, 192 magenta 255, 0, 255
with the getsize() method. gon p. Line 3 defines the second point plotted for poly- orange 255, 200, 0 pink 255, 175, 175
Graphics 2D – import java.awt.graphic2D; gon p. This method is used repeatedly to plot each point red 255, 0, 0 white 255, 255, 255
The graphics2D class is a new addition to Java 1.2. on the polygon individually. Line 4 closes polygon p. It yellow 255, 255, 0
This class adds the use of special patterns, more con- is not necessary to close a polygon; it can be left open.
trol over the width and style of the strokes, and the use Line 5 fills polygon p with the declared drawing color.
of anti-alias. Note: An “f” following the x and y is used to define a THREADS
Fill patterns are gradients that blend from one color number as a float.
to another color. The GradientPaint() method has an To fill/draw a defined drawing object, use the A thread is an object that is designed to run on its
argument at the end that defines whether or not the fill(instance) or draw(instance) method from the graphics2D own while the rest of the program is performing anoth-
gradient repeats. er task. To use a thread in an applet, implement the
class instance screen2D in the init() or main() method. Runnable interface in the class definition and define a
variable named runner with type Thread. Then, place
the following Code Example in the start() method:
AUDIO CLIPS IMAGES if (runner == null) {
Image – import java.awt.image; runner = new Thread(this);
AudioClip – import java.applet.AudioClip; runner.start();
Java 1.2 can play the following audio formats: AIFF, Java can display GIF and JPEG formatted images. To
make an image available to the applet, it must be located. }
AU, WAV, type 0 MIDI, Type 1 MIDI, and RMF. Java Place the following Code Example in the stop() method:
1.2 now supports 8 and 16-bit audio data in mono and Use an instance of the URL object to tell Java where to find
the image. The following Code Example is a URL statement if (runner != null) {
stereo. Sample rates can range from 8KHz to 48KHz. runner = null;
which tells Java where the image QSLogo.gif is located:
To load and play an audio file immediately, use the URL u = new URL(“http://www.barcharts.com/ }
play() method: images/QSLogo.gif”); Finally, place the following as a new method below start():
play p = new play(http://www.p.com/p.au); public void run() {
Once the image is located, load it into the Image object. Thread thisThread = Thread.currentThread()
To load a sound to be used repeatedly, use the To load the image, use the getImage(instance) method in while (runner ++ thisThread) {
getAudioClip() method: the init() or main() method. To draw the image on repaint();
AudioClip a = new AudioClip screen, use the drawImage(u, W, H, this) method from try {
(http://www.p.com/p.au); the graphics class instance screen. Thread.sleep(1000);
Note: The width and height of the image will be scaled } catch (InterruptedException e) {}
To play the AudioClip, use the play(instance) to match that of the W and H arguments. To make the }}
method in the init() or main() method: image its original size, replace the W with getWidth() The Java applet will repeatedly repaint the screen
Play(a); and the H with getHeight(). until the value of runner is not equal to null.

3
APPLETS USER INTERFACE
The differences between applets and applica- Components Then, inside the init() or main() method, use the
tions include: Components are objects that can be placed onto a addItem(string) method from the List class to
• Applications require a main class file to run. user interface. All components are classes and are 1.addItem(“1”);
• Applets will run on any browser that supports made by creating an object of that class. To add a • Canvases. Used in place of an interface to
Java. created component to an interface, use the display objects. To create a canvas, create an
• Applets are restricted from completing risky add(componentInstance) method inside the init() or instance of the canvas class and add the
tasks on a users machine, such as reading and main() method. The following are all components instance.
writing files, communicating with a web site found in the java.awt package:
aside from its origin site, running a program, or • Labels. Creates a box filled with copy on Layout Manager
loading stored programs. screen used to identify a component of a user Layout Managers define how components in
• Applications have none of the restrictions that interface. Labels can be created with any com- containers are arranged. To activate a layout man-
applets have. bination of two arguments (string, ager, add its instance to the init() or main(0 method
• Modern browsers do not fully support versions Label.LEFT/CENT/RIGHT). The following with the setLayout(layoutInstance) method. The
later than Java 1.1. Code Example is for a basic center aligned Help AWT has five different layout managers:
• Applications are written in its most recent ver- label showing two arguments: 1. Flow Layout. The default layout manager is
sion, Java 1.2 Label l = new Label(“Help”, Label.CENTER); the FlowLayout class. This layout places com-
ponents from left to right in the window as the
Creating Applets • Buttons. Creates a clickable button used to trig- components are added to the interface. Flow
All applets must be declared public and must be ger an action. Buttons can be created with either Layouts are created with one or three arguments
a subclass of the Applet class. To declare an applet no argument or one argument (string). The fol- (FlowLayout.LEFT / CENTER / RIGHT or
use the following form: lowing Code Example is for a basic Quit button: FlowLayout.LEFT / CENTER / RIGHT, H, V).
public class appleName extends Button quit = new Button(“Quit”); The following Code Example is for a basic cen-
java.applet.Applet { ter aligned flow layout with a horizontal gap of
• Check Boxes. Creates a box that can be checked-
Applets do not have a main() method that is off or left empty. Used to select or deselect an 10 pixels and a vertical gap of 20:
automatically called to begin. Instead, applets have option. Check Boxes can be created with either no FlowLayout f = new FlowLayout
methods that are called at different times during the argument or one argument (string). The following (FlowLayout.CENTER, 10, 20);
execution of the applet. These methods do nothing Code Example is for a basic Yes check box: 2. Grid Layout. Places components into a grid
unless they are given behavior (overridden). The Checkbox c = new Checkbox(“Yes”); of rows and columns. The first component is
following four are part of java.applet.Applet: inserted into the top left cell and the subsequent
• init() – Initialization. Used to create objects that To set the box as either checked or unchecked, use
the setState(boolean) method (true checks the components are added row by row. Grid Layouts
will be needed when the applet is initialized. are created with two or four arguments (R, C or
• start() – Starting. Starts an applet after it has box, false unchecks the box). Use the
getState(CheckboxInstance) method to return the R, C, H, V). The following Code Example is for
been initialized or after it has stopped. a basic grid layout with 7 rows and 2 columns, a
• stop() – Stopping. Called when the applet is no value of a Check Box.
horizontal gap of 10 pixels and a vertical gap of
longer displayed, such as when the page is The CheckboxGroup object is used to place 20 pixels:
closed or hidden. Check Boxes in groups. This is helpful if the user GridLayout b = new GridLayout(7, 2, 10, 20);
• destroy() – Destruction. The last step before an must select only one choice from the group. To
applet is closed. Used to end running threads or make a group, first create an instance of the 3. Border Layout. Creates a container with
release any running objects. CheckboxGroup object. Then, create an instance five sections: north, south, east, west, and cen-
of the Checkbox object with three arguments ter. The four compass sections take the area
The following three methods are part of they need and the center gets the space left over.
java.awt.Component: (String, GroupInstance, boolean) instead of one.
The boolean is used in place of the Border Layouts are created with no argument or
• paint() – Painting. Used to display something two arguments (H, V). The following Code
on screeen. setState(boolean) method.
Example is for a basic border layout with a hor-
• repaint() – Repainting. Requests the Java win- • Text Fields. Creates components for one line of izontal gap of 10 pixels and a vertical gap of 20
dowing system to repaint, or update, the screen editable text. Text Fields can be created with any pixels:
as soon as possible. combination of two arguments (string, W). The fol- BorderLayout b =new BorderLayout(10, 20);
• update() – Updating. Redraws the applet by lowing Code Example is for a TextField with the
calling paint(). Then, inside the init() or main() method, use the
string, first name inside and a width of 25 characters: add(“north”/“south”/“east”/“west”/“center”,
Java.awt TextField f = new TextField(“first name”, 25);
component) method from the BorderLayout
The Abstract Windowing Toolkit (AWT) adds • Text Areas. Creates components for multiple class to place items inside the designated section.
graphics, fonts, color and other interactive pieces lines of editable text. Text Areas can be created 4. Card Layout. Creates a layout that holds mul-
to a program. This package contains classes that tiple containers for the same area. This layout
will help create a Graphical Users Interface (GUI). with any combination of three arguments (string,
W, H). The following Code Example is for a allows one container to be seen at a time, hiding
TextArea with the string, Comments inside and a the other containers. A series of tab buttons are
width of 25 and a height of 50 characters: used to represent a hidden container and can be
DIGITAL SIGNATURES TextArea a = new TextArea(“Comments”, 25, pressed to reveal that container. To activate the
The Java sandbox prevents applets from doing 50); Card Layout, first, create an instance of the
malicious things to an end user’s system by pre- CardLayout class. Then, use the setLayout()
• Scrollbars & Sliders. Creates a Scrollbar used to method in the init() or main() method. To add
venting access to his/her system resources. As a view different areas of the attached window. Scrollbars
result, any language feature that has potential for containers to a Card Layout, use the add(string,
can be created with no argument or five arguments: container) method inside the init() or main()
abuse has been blocked from use in applets. This • Scrollbar(); - Creates a vertical scrollbar.
includes the following: method. The string argument would represent the
• Scrollbar(Scrollbar.HORIZONTAL/VERTI- container on its tab button.
• Deleting files from the end user’s machine. CAL); - Creates a scrollbar defined either hori-
• Reading files on the end user’s machine. 5. Grid Bag Layout. Places components into a
zontal or vertical. grid of rows and columns. A component can
• Writing files to the end user’s machine.
• Retrieving information about a file on the end • Scrollbar(Scrollbar.HORIZONTAL/VERTI- cover more than one grid, and an individual cell
CAL, V, W/H, N, X); - Creates a scrollbar does not have to be proportioned to the other
user’s machine.
• Displaying a window without the standard “Java defined either horizontal or vertical, initial cells. To activate the Grid Bag Layout, first cre-
applet window” warning. value of V, defined width or height W/H, mini- ate an instance of the GridBagLayout class and
• Making a network connection from the end mum value N, and maximum value X. the GridBagConstrains class (usually the
user’s machine to any machine other than the instance name is constraints). Then, use the
Containers method named buildConstraints() with seven
one that delivered the web page containing the Containers are components that contain other
applet. arguments:
components. The following are all container com- Void buildConstraints(GridBagConstraints
Java 1.2 provides applets with the ability to lift ponents found in the java.awt package: gbc, int gx, int gy, int gw, int gb, int wx, int wy);
these restrictions and run with the full privileges as • Choice List. Creates a component that lets a Gbc.gridx = gx; – x coordinate of the cell
a Java application. The applet must come from a single item be picked from a pull-down list. To Gbc.gridy = gy; - y coordinate of the cell
trusted applet provider and must have a digital sig- create a Choice List, first create an instance of the Gbc.gridwidth = gw; - Number of columns cov-
nature to verify its authenticity. Choice object:
A digital signature is an encrypted file or a ered by the component
Choice c = new Choice(); Gbc.gridheight = gh; - Number of rows covered
group of encrypted files that download with an
Then, inside the init() or main() method, use the Gbc.weightx = wx; - Percentage of the Grid’s
applet. These files, called certificates, imply who
and where the applet came from. addItem(string) method from the Choice class to width covered by the component
c.addItem(“1”); Gbc.weighty = wy; - Percentage of the Grid’s
Certificate authorities verify the identity of an
applet provider and will establish trust for the • Scrolling List. Creates a component that lets height covered
provider. These groups are not affiliated with any multiple items be picked from a scrolling list. This method is used to defined the properties
applet developers and have an established reputa- Scrolling Lists can be created with any combina- for individual components and must be overrid-
tion as reliable companies. The following are two tion of two arguments (V< boolean). The follow- den in init90 of main() for every component
certified authority groups: ing Code Example is for a Scrolling List with 5 added to the layout. Use the setConstraints(com-
• VeriSign – www.verisign.com visible items and can have multiple selections: ponent, constraints) method to set the overrid-
• Thawte Certification – www.thawte.com List l = new List(5, true); den buildConstraints() for the component.
4
EXCEPTION HANDLING EVENT HANDLING PANELS & FRAMES
Events that cause Java programs to fail are An event is anything that the end user does or can Panels
called exceptions. When an exception is thrown, do while a program is running. Whether or not the A panel is a container that is used to group inter-
an instance of the class Throwable is created. event is handled by the program is up to the devel- face components together. Each panel is filled
Every exception has a subclass of Throwable; most oper of the program. All events generate an instance with components, using its own layout manager,
are defined in the Java class library. of the Event class. This class explains where, when, before being placed in a larger container. A panel
To catch an exception before it is thrown, pro- what, etc. about the current event. All basic mouse is created using the following statement:
tect it by placing the suspicious method inside of a methods look exactly the same aside from the Panel p = new Panel()
try block; then test for and deal with exceptions method name. A panel’s layout manager is set by calling the
inside of a catch block. Code Example: setLayout() method for that panel. Components
This Code Example is a basic try … catch block: Public boolean mouseMethod(Event evt, x, y) are added by calling the panel’s add() method.
try{ (See: User Interface)
These methods have three parameters: the Event
//suspicious code class instance, and the x and y coordinates where the Frames
}catch (exceptionClass ObjectName) { event occurred. A frame is a platform-specific window with a
// code executed if an exception is caught title, menu bar, close boxes, resize handles and
} Handling Mouse Clicks other window features. It is used by Java applets to
When a user clicks a mouse, two events are gen- produce separate windows and by Java applications
Note: A try block can have multiple catch blocks. erated - mouse down and mouse up. This split is
In multiple catch blocks, the first catch block to hold the contents of that application. To create a
used for assigning different events for the different frame, use one of the following constructors:
that matches will be executed and the rest will stages of a mouse click. The mouseDown() and the • new Frame() – creates a basic frame.
be ignored. mouseUp() methods define the starting location for • new Frame(String) – creates a basic frame with
A third block can be used as the clean-up block. the x and y coordinates. a title.
The finally block forces an action to take place Handling Mouse Movements Frames are containers, like panels, and can add
whether or not the exception was thrown. To use If the mouse is being moved with the mouse but- components like panels, using the add() method.
this block, add the following code example below ton pressed, it is a drag. If the button is not pressed, (See: User Interface)
the try … catch block: it is a move. The mouseDrag() and mouseMove() There are some necessary methods needed to
}finally{ methods’ x and y coordinates produce the new loca- use frames.
// mandatory action tion, not its starting location. • Set a specific frame size:
}
Handling Keyboard Events frameName.resize(w,h);
To mark a method as a possible exception, use A keyboard event occurs whenever a key is • Make the frame size as small as possible while
the throws clause. Place the word throws and the pressed on the keyboard. The keyDown() method is still able to hold its components:
exception or exceptions that might be thrown after used when a key is pressed, and the keyUp() method frameName.pack();
the closing parentheses ()) and before the opening is used when a key is released. • Make a window visible (all frames start out
brace ({) in the method statement. Code Example: invisible):
Code Example: public boolean keyMethod(Event evt, int key) frameName.show();
Public void printTest() throws IOException { • Make a window invisible:
These methods have two parameters: the Event frameName.hide();
The above line will let others know that the class instance and the integer representing the
method may throw a specific exception. Unicode character values. In order to use the
Throwing an exception can be done by accident Unicode representation as a character, the integer
must be casted using the following statement: SWING
or can be executed on purpose. To force an excep-
Currentchar = (char)key; Swing is the new windowing class included in
tion to be thrown, create an instance of the excep-
tion class, then use the throw statement. Java has keys that are already programmed. The fol- Java 1.2. This windowing class creates interfaces
Code Example: lowing is a list of default keys and their class variable: in the style of the native operating system. Swing
IOException() io = new IOException; Event.HOME Home key also creates an interface style unique to Java 1.2
Throw io; Event.END End key called metal. To use Swing, import the swing class
Event.PGUP Page Up key with this statement:
Java has defined every known exception in the Event.PGDN Page Down key import java.awt.swing.*;
Java class library, but new exceptions can always Event.UP Up arrow
be created. To create a new exception, inherit from Swing components work like the components in
Event.DOWN Down arrow the Abstract Windowing Toolkit but are subclasses
an existing exception similar to the one being cre- Event.LEFT Left arrow
ated. If there are no similar exceptions, inherit Event.RIGHT Right arrow of the JComponent class. Swing applications are
from the Exception class. Event.F1 F1 key subclasses of the class JFrame. Components and
Exceptions normally have two constructor containers are added to a content pane, which rep-
methods. The first method is defined with no argu- Handling Component Events resents the full area of the frame in which compo-
ments, the second is defined with one string argu- Interface components react without the use of the nents can be added, then the content pane is added
ment. Typically, the super() method would be mouseDown() and the mouseUp() methods; that is to the frame.
called to make sure the string argument went to the handled by the component. The following are steps to adding components
correct location. Action events indicate that a component has been to a content pane:
Code Example: activated. To intercept an action event, use the 1. Create a JPanel object.
public class QSException extends Exception { action() method: 2. Use the add() method to add all components and
public QSException () {} Public boolean action(Event evt, Object arg) containers to the JPanel.
public QSException(String bar) { The second argument in the action method calls a 3. Use the setContentPane(Jpanel) method to make
super(bar); specific type of argument depending on the type of the JPanel the content pane.
} component generating the action. The following is a Labels
} list of components and the argument types: The JLabel class is comparable to the AWT
If a method is called with a throws clause, do Buttons String – the label of the button Label class. JLabel can include icons and can
one of the following: Check boxes Boolean – always true adjust alignment between LEFT, RIGHT, and
Radio button Boolean – always true CENTER.
• Use try and catch statements to deal with the Choice menu String – the label of the item selected
exception. • JLabel(String,int) - Specified text and alignment
Text fields String – the text inside the field • JLabel(String, Icon, int) – Specified text, icon
• Add a throws clause and pass the exception up
the calling chain. The first thing to do inside an action method is to and alignment
• Catch and rethrow the exception. test for which component generated the action. Add
this line of code below the action() method statement: Buttons
The following is a list of cases where an excep- If (evt.target instanceof component)
The JButton class is comparable to the AWT
tion should not be used: Button class. JButton can include text, icon, or
• If the exception is expected and can be avoided. This is an if statement. evt.target calls the target combinations of both.
• If the user is entering an integer, it is better to method from the Event class. Instanceof checks for • JButton(String) – Specified text
test for an integer than to throw an exception. the specified component. • JButton(Icon) – Specified icon
Testing is always better than error handling. Focus • JButton(String, Icon) – Specified text and icon
• Only use exceptions when the results are out of The focus is the component of an interface that is Text Fields
your control. A series of tests will run faster currently active. There are two events for focus: got The JTextField class differs from the AWT
than throwing an exception. focus and lost focus. These two events have their TextField class. JTextField does not support the
• The more exceptions thrown, the more complex own methods: gotFocus() and lostFocus(). The setEchoChar(char) method to obscure input.
the code. It is better to throw only the exceptions method statement looks very similar to the action() Instead, Swing has a JPasswordField class that sup-
that have a reasonable chance of happening. method statement: ports the setEchoChar(char) to obscure input.
The Java compiler will warn you if it finds public boolean gotFocus(Event evt, Object arg) • JTextField(int) – Specified width
errors or exceptions that have not been resolved. If public boolean lostFocus(Event evt, Object arg) • JTextField(String, w) – Specified text and
an exception is thrown on purpose without being The focus is used most with text areas and text width
handled, the compiler will not catch it. This could fields. Once the focus has been placed in a specific • JPasswordField(int) – Specified width
cause fatal errors to occur if the exception is not text area or text field, the keyboard events will only • JPasswordField(String, w) – Specified text and
caught and resolved. occur in there until the focus has been shifted. width

5
SWING CONTINUED . . .

Text Areas any listener component. The string argument should SWING DIALOG BOXES
The JTextArea class is the same as the AWT be the action command’s desired text.
TextArea class. • Adjustment listeners are generated when a The JOptionPane class has several methods that will
• JTextArea(w, h) – Specified width and height. component is adjusted. The addAdjustmentListener() create standard dialog boxes. Dialog boxes are an
• JTextArea(String, w, h) – Specified text, width, method can be used with JScrollBar components. effective way to communicate with the user without
and height. The AdjustmentListener interface must be imple- having to create a new class, add components, or write
mented to handle these events. Add this statement to event handlers to take input. The standard dialog boxes
Check Boxes handle everything automatically.
The JCheckBox class is the same as the AWT the code in order to handle an adjustment event:
CheckBox class with the addition of icon labels. public void adjustmentValueChange Confirm Dialog Boxes
• JCheckBox(String) – specified text label. (AdjustmentEvent evt) Confirm dialog boxes asks a question and waits for
• JCheckBox(String, boolean) – Specified text label To find the scrollbar’s (bar) value use this line: either the yes, no, or cancel button to be clicked.
and on/off. Int newValue = bar.getValue(); Code Example:
• JCheckBox(Icon) – Specified Icon. Int response = JOptionPane.showConfirmDialog
• JCheckBox(Icon, boolean) – Specified icon and • Focus listeners are generated when a component (null “Are you sure you want to continue”,
on/off. gains or loses focus. The addFocusListener() method JOptionPane.YES_NO_OPTION,
• JCheckBox(String, Icon) – Specified text label and can be used with all Swing components. The JOptionPane.ERROR_MESSAGE);
icon. FocusListener interface must be implemented to han- 1. Set the integer response to showConfirmDialog().
• JCheckBox(String, Icon, boolean) – Specified text dle these events. Add the following two statements to If the component argument is specified as null, the
label, icon and on/off. the code in order to handle a focus event: dialog box will appear in the center of the screen.
Use the ButtonGroup class to group Check boxes, • public void focusGained(FocusEvent evt) The object argument will either be a string or an
Radio buttons, and Buttons. Only one component in a • public void focusLossed(FocusEvent evt) icon. The object will appear in the dialog box.
group can be on at one time. Create a ButtonGroup 2. Set the JOptionPane button argument. There are
• Item listeners are generated when an item is two combinations of buttons: YES_NO_OPTION
object and use the add(component) method to add changed. The addItemListener() method can be used
components to the group. and YES_NO_CANCEL_OPTION.
with JButton, JCheckBox, JComboBox, and 3. Set the argument for the kind of confirm dialog box.
Radio Buttons JRadioButton components. The ItemListener inter- This will let Java know what to name the box and
The JRadioButton class is the same as the AWT face must be implemented to handle these events. what icon to display. There are five different com-
RadioButton class with the addition of icon labels. Add this statement to the code in order to handle an binations: ERROR_MESSAGE, INFORMA-
The JRadioButton statements are exactly the same as item event: TION_MESSAGE, PLAIN_MESSAGE, QUES-
the JCheckBox statements above. public void itemStateChanged(ItemEvent evt) TION_MESSAGE, and WARNING_MESSAGE.
Choice Lists To determine which item (pick) had the event use this Input Dialog Boxes
The JComboBox class is similar to the AWT Choice line: Input dialog boxes prompt the user for new input.
class, but choice lists are just one possible implemen- Object newPick = evt.getItem(); This dialog box has the same options as the confirm
tation with this Swing class. dialog box, but in place of the button argument, the
Follow these steps to create a JComboBox: • Key listeners are generated by a user entering text
on the keyboard. The addKeyListener() method can input dialog box has a string for naming the box. To
1. Create a JComboBox() method with no arguments. use an input dialog box, set the String response to
2. Use the addItem(object) method to add items to the be used with all Swing components. The KeyListener
interface must be implemented to handle these events. showInputDialog().
list.
3. The setEditable(boolean) method will decide Add the following three statements to the code in Message Dialog Boxes
whether the combo box is editable (true) or not order to handle a key event: Message dialog boxes display a message. This dia-
(false). If the boolean is set to false, the combo box • public void keyPressed(keyEvent evt) log box is identical to the input dialog box, but it does
is considered a choice list. • public void keyReleased(keyEvent evt) not return a response. To use a message dialog box, set
• public void keyTyped(keyEvent evt) the String response to showMessageDialog().
Scrollbars
The JscrollBar class is identical to the AWT scrollbars. • Mouse Listeners are generated by mouse clicks Option Dialog Box
• JScrollBar(int) – Specified HORIZONTAL or VER- and mouse movements in and out of an area. The Option dialog boxes combine confirm, input and
TICAL addMouseListeners() method can be used with all message dialog boxes.
• JScrollBar(int, sv, s, n, x) – Specified HORIZON- Swing components. The MouseListener interface
TAL or VERTICAL, starting value, size, minimum must be implemented to handle these events. Add the
value, and maximum value following five statements to the code in order to han- Java is not the same as
Icons dle a mouse event: JavaScript. JavaScript was
An icon is a small graphic, usually a GIF file, that can • public void mouseClicked(MouseEvent evt) created by Netscape, using the
be used on labels, buttons, check boxes, and radio but- • public void mouseEntered(MouseEvent evt) same name, in hopes of making as
tons to identify its component. An icon is created in • public void mouseExited(MouseEvent evt) big a splash as Java.
much the same way as an Image object. The following • public void mousePressed(MouseEvent evt)
code example creates an icon named Iname from the file • public void mouseReleased(MouseEvent evt) Here are some popular Java sites:
Iname.gif and places it on the Swing component Cname: QUICK
QUICK www.javasoft.com
To determine the x and y coordinates of the mouse, www.gamelan.com
ImageIcon Iname = new ImageIcon(“Iname.gif”); use the getPoint() method. To find out how many TIP
JComponent Cname = new JComponent(Iname);
times the mouse button was clicked, use the
Look and Feel getClickCount() method. To find the mouse’s x or y CREDITS PRICE
The JDK 1.2 has three choices for look and feel of position, use the get(X) or the get(Y) method respec- Author: Michael D. Adam U.S. $5.95
programs. tively of the Mouse Event class. CAN $8.95
• A Windows 95 and Windows NT look and feel. • Mouse motion listeners will track all
• A Motif X-Windows system look and feel (UNIX). movement by a mouse over a component. The ISBN-13: 978-142320809-9
• Metal, Swing’s new cross-platform, look and feel. addMouseMotionListener() method can be used with ISBN-10: 142320809-9
To set the look and feel of the application, use the all Swing components. The MouseMotionListener
setLookAndFeel(LookAndFeel) method. To get the interface must be implemented to handle these events.
look and feel that can be used on the specific platform, Add the following two statements to the code in order
use one of the following get() methods: to handle a mouse motion event:
• GetCrossPlatformLookandFeelClassName() – • public void mouseDragged(MouseMotionEvent
Returns the Metal look and feel. evt) Java and the JDK are products of Sun Microsystems.
• GetSystemLookAndFeelClassName() – Returns • public void mouseMoved(MouseMotionEvent evt) All information in this chart is based on version 1.2 of
the specific system look and feel. the Java programming language. This language is
• Window listeners are generated when windows evolving from version to version, and some information
are adjusted. The addWindowListener() method can may carry over into other versions of the language.
be used with all JWindow and JFrame components.
0SWING EVENT HANDLING The WindowListener interface must be implemented Nov 2008
Swing handles events through a set of classes called to handle these events. Add the following seven state- All rights reserved. No part of this
event listeners. After a component has been made, call ments to the code in order to handle a window event: publication may be reproduced or
transmitted in any form, or by any
an event listener method on the component to associate • public void windowActivated(WindowEvent evt) means, electronic or mechanical,
the listener with the component. The following is a list • public void windowClosed(WindowEvent evt) including photocopy, recording, or
of event listeners: • public void windowClosing(WindowEvent evt) any information storage and
• Action listeners are generated by a user taking • public void windowDeactivated(WindowEvent evt)
retrieval system, without written
permission from the publisher.
an action on a component. The addActionListener() • public void windowIconified(WindowEvent evt) © 2001 BarCharts, Inc. Boca
method can be used with JButton, JCheckBox, • public void windowDeiconified(WindowEvent evt) Raton, FL
JComboBox, JTextField, and JRadioButton compo- • public void windowOpened(WindowEvent evt)
nents. The ActionListener interface must be imple-
mented to handle these events. Add this statement To import all event listeners use the following statement: visit us at
to the code in order to handle an action event:
public void action Performed(ActionEvent evt)
import java.awt.event.*; quickstudy.com
Note: If more than one component in the interface has
Instead of the getSource() method, action listener the listener, Java must figure out which component Customer Hotline # 1.800.230.9522
components can be given an Action command. The was used. Add this line below the event handling line: We welcome your feedback so we can maintain
setActionCommand(string) method can be added to Object source = evt.getSource(); and exceed your expectations.

You might also like