Full HTML for

Basic foilset Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit

Given by Geoffrey C. Fox, Nancy McCracken at NAVO Tutorial on Sept 23 1998. Foils prepared Sept 21 1998
Outside Index Summary of Material


This version of Part3 is Fully Upgraded to Java1.1 with critical AWT changes
In Part 1 and 2 of the Tutorial We Covered:
  • Overview including History and alpha versus production issues
  • Comparison of Java and Javascript
  • Overall Java Philosophy and Features including security etc.
  • Java Programming Language
  • Introduction to Applications,Applets and their Invocation from HTML
  • "Hello World" and Basic Graphics Applets
  • Object Oriented and Class Structure
  • Methods, Constructors etc.
  • Interfaces
  • Exceptions
In This Part of the Java Tutorial We Cover:
Introduction to Threads
Graphics in more detail
  • Animator Class
  • Downloading and Drawing Images
Abstract Windowing Toolkit
  • Keyboard and Mouse Events
  • Components, Actions, Layouts
And in the Remaining Part of the Java Tutorial We Cover:
  • Threads in More Detail
  • Useful Classes such as Object String etc.
  • Networking and I/O
  • Futures and HPCC Implications

Table of Contents for full HTML of Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit

Denote Foils where Image Critical
Denote Foils where Image has important information
Denote Foils where HTML is sufficient
denotes presence of Additional linked information which is greyed out if missing

1 Java Tutorial 1998 Part 3: Graphics and the Abstract Windowing Toolkit
2 Applets and Graphics
3 The java.awt.Graphics class
4 Simple Graphics Examples for Foil 4 Methods for drawing in the Graphics Class
5 Graphics is Event-Driven: paint method
6 Changing Graphics: repaint method
7 FontMetrics example for Foil 7 The java.awt.Font and FontMetrics Class
8 Drawing more simple shapes with new colors The java.awt.Color Classes
9 More Graphics Examples for Foil 9 Graphics Examples
10 Introducing a Single Thread
11 Introduction to Threads
12 Example showing the standard thread methods
13 A digital clock with one thread Example showing thread methods, continued
14 Motion (or Animation) Example using threads and parent/child hierarchy
15 Moving Rectangles showing an applet thread and parent/child classes for Foil 15 Designing the Classes
16 Moving Rectangles showing an applet thread and parent/child classes for Foil 16 The Class Hierarchy of this example
17 Images and Double Buffering
18 Getting Images Downloaded
19 Drawing Images to the applet window
20 Look in the init method to see the use of prepareImage to determine when image downloading is finished. Image Downloading -- imageObserver, MediaTracker
21 An image example An Image Drawing Example
22 Flickering in Applets and its Solution
23 The default Update(Graphics g) Method
24 Double Buffering to Reduce Flicker - I
25 Double Buffering to Reduce Flicker - II
26 Movable Objects example with double buffering and boundary checking for Foil 26 Double Buffering
27 Abstract Windowing Toolkit (AWT):
28 AWT GUI Components
29 Picture of the AWT Component Class and its inheritance
30 Basic AWT Components
31 Labels for Foil 31 Basic AWT Component: Label
32 Buttons for Foil 32 Basic AWT Component: Button
33 The AWT Event Model
34 Setting up ActionEvents for a Button
35 API for class Event The Event Classes
36 TextFields and TextAreas for Foil 36 AWT Components -- Text Fields & Areas
37 Checkboxes for Foil 37 AWT Components -- Checkbox
38  for Foil 38 AWT Components -- Radio Buttons , CheckboxGroup
39 The remaining basic Components for Foil 39 Some Further AWT Components -- typical subunits of panels
40 API for class KeyEvents Keyboard and Mouse Events
41 API for class MouseEvent Mouse Events
42 MouseEvents examples for Foil 42 Using Mouse Events for User Interaction
43 Separate Classes for Event Listeners
44 Adapter classes for Foil 44 Adapter Classes
45 Abstract Windowing Toolkit (AWT): Layouts
46 Layout of Components in a Panel
47 Brief Description of LayoutManagers
48 BorderLayouts for Foil 48 Description and Example of BorderLayout
49 API for class FlowLayout FlowLayouts in detail
50 GridLayouts for Foil 50 GridLayouts
51 More Layout examples for Foil 51 Hierarchical Use of Layouts
52 Abstract Windowing Toolkit (AWT): More Components
53 API for class Canvas AWT Component: Canvas
54 Window and Frame for Foil 54 Some Further AWT Components: Window (Frame and Dialog)
55 classes for menus in frames for Foil 55 Frames can have MenuBars
56 API for class Dialog Dialog Boxes
57 new component classes for Foil 57 New Components: ScrollPanes and PopupMenus
58 PPT Slide

Outside Index Summary of Material



HTML version of Basic Foils prepared Sept 21 1998

Foil 1 Java Tutorial 1998 Part 3: Graphics and the Abstract Windowing Toolkit

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
http://www.npac.syr.edu/projects/tutorials/Java/
Instructors: Geoffrey Fox , Nancy McCracken
Syracuse University
111 College Place
Syracuse
New York 13244-4100

HTML version of Basic Foils prepared Sept 21 1998

Foil 2 Applets and Graphics

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index

HTML version of Basic Foils prepared Sept 21 1998

Foil 3 The java.awt.Graphics class

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
The AWT has two different schemes for creating all or parts of applet windows:
  • A high-level scheme where a Layout manager decides how to place components like buttons and textfields in the window (described later).
  • A low-level scheme where methods draw graphics objects to the window and must say where to place them in terms of pixels.
(0,0) (width,0)
(0,height) (width,height)
Java Graphics Pixel Coordinate System

HTML version of Basic Foils prepared Sept 21 1998

Foil 4 Methods for drawing in the Graphics Class

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index Simple Graphics Examples for Foil 4
Graphics class has methods to construct basic two dimensional images
  • (all parameters are ints unless otherwise indicated)
  • x, y pixel locations refer to the upper left corner of the object to be drawn (except for strings)
drawString (String text, x, y)
drawLine (x1, y1, x2, y2)
drawRect (x, y, width, height), fillRect (...),
drawOval (...), fillOval (...),
drawRoundRect (x, y, width, height, arcWidth, arcHeight)
  • for a rectangle with rounded corners!,
draw3DRect (x, y, width, height, Boolean b)
  • (to get shadow effect as in buttons - if b is true, it's raised),
drawArc (x, y, width, height, startAngle, arcAngle), fillArc(..),
drawPolygon(int xPoints[], int yPoints[], n);

HTML version of Basic Foils prepared Sept 21 1998

Foil 5 Graphics is Event-Driven: paint method

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
In every applet or windows application, the windowing system creates an Image with a Graphics object to keep track of the state of the window.
In order to draw or write text to the window, you must override the paint method:
  • public void paint(Graphics g)
The Graphics object g has a current color and font that can be changed by methods
The window system can be interrupted for various reasons - the user resized it or some other window was put on top of it and then removed - and it does not save a copy of the pixels. Instead it calls the paint method. So even if you only draw one window, paint can be called many times.

HTML version of Basic Foils prepared Sept 21 1998

Foil 6 Changing Graphics: repaint method

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
Most applets and windows applications want to change what is drawn on the screen over its lifetime. This can be a sequenced animation, response to user input or mouse events, and so on.
Whenever you want to redraw the screen, call
  • public void repaint(); // note no arguments
Repaint gets the graphics context g and creates a thread to call update(g), which calls your paint method. So all your drawing changes can also be put in paint.
One draws a sequence of text and shapes to define the screen, where the position of the object in the screen is given by pixel coordinates. If one object overlaps another, the latest one drawn covers up the area of overlap.
  • The exception to this is XOR graphics, which may be used to temporarily highlight a particular color. This is an advanced technique as other colors will also be affected.

HTML version of Basic Foils prepared Sept 21 1998

Foil 7 The java.awt.Font and FontMetrics Class

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index FontMetrics example for Foil 7
Graphicsinstance.setFont(particularFont) will set the current Font in the instance Graphicsinstance of the Graphics class to the value particularFont of class Font.
The class Font has an important constructor used as in
Font MyFont = new Font("TimesRoman", Font.PLAIN ,36);
  • where one can also use Courier, Helvetica, ZapfDingbats, . . ., Monospaced, Serif, SansSerif, Dialog
  • Font.PLAIN, Font.BOLD, Font.ITALIC are possible text styles
FontMetrics fm = getFontMetrics(particularFont); // allows one to find out about the font
  • fm.stringWidth("text"); // returns pixel width of string "text"
  • fm.getHeight(); // returns total height of highest Font character
  • getAscent(),
  • getDescent(),
  • getLeading(),
Drawstring uses leftmost baseline point as (x,y)
Nancy
leading
ascent
descent
baseline
}
height

HTML version of Basic Foils prepared Sept 21 1998

Foil 8 The java.awt.Color Classes

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index Drawing more simple shapes with new colors
Color c = new Color (redvalue, greenvalue, bluevalue); red/green/bluevalue can be specified as integers in 0 ... 255 or floating point numbers from 0 to 1.
c is generated as a Color in RGB format.
graphicsobject.setColor(c); // sets current color in graphicsobject which is used for all subsequent operations
There are particular Color instances already defined such as
  • Color.white equivalent to Color(255,255,255)
  • Color.black as equivalent to Color(0,0,0)
  • Color.pink as equivalent to Color(255,175,175)
  • also orange, cyan, magenta, yellow, gray, lightGray,
  • darkGray, red, green, blue

HTML version of Basic Foils prepared Sept 21 1998

Foil 9 Graphics Examples

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index More Graphics Examples for Foil 9
Check out more examples
  • Color boxes generates colors using a random number generator.
  • Another example shows more graphics drawing. Note that drawing arcs is done with respect to the following angle representation:
  • drawArc (x, y, width, height, startAngle, arcAngle)
180
270
90

HTML version of Basic Foils prepared Sept 21 1998

Foil 10 Introducing a Single Thread

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
(See later for in-depth discussion of thread use)

HTML version of Basic Foils prepared Sept 21 1998

Foil 11 Introduction to Threads

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
A thread is a single sequential flow of control within a process.
If a process has more than one thread, then each thread executes concurrently.
Any Java applet that has extensive execution or loops to repaint the window must run as a concurrent thread with the browser window.
To make an applet with a thread:
  • Change your applet definition to add "implements Runnable", the interface for threads.
  • Include an instance variable for the thread of your applet.
  • Have a start() method that creates a thread and starts it running and a stop() method which stops it running.
  • Implement a run() method containing the body of your applet code.

HTML version of Basic Foils prepared Sept 21 1998

Foil 12 Example showing the standard thread methods

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
These applet start and stop methods can always be used to start and stop the thread.
import java.awt.*;
import java.util.Date;
public class DigitalClock extends java.applet.Applet
implements Runnable
{ Font theFont = new Font("TimesRoman", Font.BOLD, 24);
Date theDate;
Thread runner;
public void start ( )
{ if (runner == null)
{ runner = new Thread(this); runner.start ( ); }
}
public void stop ( )
{ if (runner != null)
{ runner.stop ( ); runner = null; }
}

HTML version of Basic Foils prepared Sept 21 1998

Foil 13 Example showing thread methods, continued

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index A digital clock with one thread
The body of the applet is in the run method, in this case a loop to keep showing the date.
public void run ( )
{ while (true)
{ theDate = new Date ( );
repaint ( );
try { Thread.sleep ( 1000); }
catch ( InterruptedExecution e) { }
}
}
public void paint ( Graphics g )
{ g.setFont ( theFont );
g.drawString ( theDate.toString ( ), 10, 50 );
}
}

HTML version of Basic Foils prepared Sept 21 1998

Foil 14 Motion (or Animation) Example using threads and parent/child hierarchy

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index

HTML version of Basic Foils prepared Sept 21 1998

Foil 15 Designing the Classes

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index Moving Rectangles showing an applet thread and parent/child classes for Foil 15
We want to make applets that can have objects of different shape moving across the applet window.
  • The first applet will have two rectangles.
  • We will represent each rectangle as an instance of a class mRectangle.
  • Then the applet will have a thread that loops, and each time around the loop, will draw the rectangles in a new position.
We will design a hierarchy of classes to represent various shapes (including rectangles).
  • We define a parent class for movable point objects. Each instance of this class is represented by an x,y location, by a dx,dy offset for the object to move, and a color for the object. This example also illustrates data encapsulation, where users of the class must use methods to get or set data of the class.
  • A child class will represent rectangles by adding variables for width and height. It will also override the paint method to draw rectangles.
  • Other shapes are easily constructed as children of the rectangle class by overriding the paint method to draw a new shape.

HTML version of Basic Foils prepared Sept 21 1998

Foil 16 The Class Hierarchy of this example

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index Moving Rectangles showing an applet thread and parent/child classes for Foil 16
Applet
mRectApplet
variables:
mPoint object[ ]
methods:
init
run
start
stop
update
paint
mPoint
variables:
int x, y, dx, dy
Color color
methods:
setDelta
setColor . . .
move
paint
mRectangle
int w, h
paint
checkBoundary . . .
mOval
paint
mTriangle
paint
uses

HTML version of Basic Foils prepared Sept 21 1998

Foil 17 Images and Double Buffering

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index

HTML version of Basic Foils prepared Sept 21 1998

Foil 18 Getting Images Downloaded

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
The Applet class provides a method getImage, which retrieves an image from a web server and creates an instance of the Image class.
Image img =
  • getImage(new URL("http://www.tc.com/image.gif"));
Another form of getImage retrieves the image file relative to the directory of the HTML or the directory of the java code.
  • Image img = getImage(getDocumentBase(), "images/image.gif");
  • Image img = getImage(getCodeBase(), "images/image.gif");

HTML version of Basic Foils prepared Sept 21 1998

Foil 19 Drawing Images to the applet window

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
The Graphics class provides a method drawImage to actually display the image on the browser screen.
  • void paint ( )
    • { g.drawImage ( img, 10, 10, this) ; }
  • where the top left corner of the image will be drawn at (x,y) position (10,10)
  • use "this" as the ImageObserver argument, even if you don't use the ImageObserver to control downloading
You can also scale the image to a particular width and height.
  • void paint ( )
    • { g.drawImage ( img, 10, 10, w, h, this) ; }

HTML version of Basic Foils prepared Sept 21 1998

Foil 20 Image Downloading -- imageObserver, MediaTracker

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index Look in the init method to see the use of prepareImage to determine when image downloading is finished.
When drawImage is called, it draws only the pixels of the image that are already available.
Then it creates a thread for the imageObserver. Whenever more of the image becomes available, it activates the method imageUpdate, which in turn call paint and drawImage, so that more of the image will show on the screen.
The default imageUpdate doesn't work if you are double buffering the window in which the image appears.
More control over showing the image as it downloads can be obtained by working with the MediaTracker class, using methods that tell you when the image has fully arrived.
  • Another method is prepareImage(MyImage, this);
    • which returns a boolean that is true when image is fully downloaded.

HTML version of Basic Foils prepared Sept 21 1998

Foil 21 An Image Drawing Example

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index An image example
This example shows how to get the actual height and width of the image to use in scaling the image under java program control.
import java.awt.*
public void class Drawleaf extends java.applet.Applet
{ Image leafimg;
public void init ( )
{ leafimg = getImage(getCodeBase( ),"images/Leaf.gif");
}
public void paint ( Graphics g )
{ g.setFont ( theFont );
g.drawString ( theDate.toString ( ), 10, 50 );
}
}

HTML version of Basic Foils prepared Sept 21 1998

Foil 22 Flickering in Applets and its Solution

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
Unless you are careful, dynamic applets will give flickering screens
This is due to cycle
  • repaint()
  • update(g) clearing screen
  • paint(g) drawing new screen .....
  • where flicker caused by rapid clear-paint cycle.
There are two ways to solve this problem which involve changing update() in different ways
  • 1: Change update() either not to clear screen at all (because you know paint() will write over parts that are to be changed) or to just clear the parts of the screen that are changed
  • or 2:Double Buffering

HTML version of Basic Foils prepared Sept 21 1998

Foil 23 The default Update(Graphics g) Method

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
This sets background color and initializes applet bounding rectangle to this color
  • public void update(Graphics g)
    • {
    • g.setColor(getBackground());
    • g.fillRect(0,0,getSize().width,getSize().height);
    • g.setColor(getForeground());
    • paint(g);
    • }
  • getBackground() and getForeground() are methods in component class
  • fillRect() is a method in Graphics class

HTML version of Basic Foils prepared Sept 21 1998

Foil 24 Double Buffering to Reduce Flicker - I

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
Here you have two "graphics contexts" (frame buffers of the size of the applet), and you construct the next image for an animation "off-line" in the second frame buffer.
This frame buffer is then directly copied to the main applet Graphics object without clearing image as in default update()
In init(), you would create the frame buffer:
  • Image OffscreenImage; // Place to hold Image
  • Graphics offscreenGraphics; /* The second graphics context of offscreenImage */
  • offscreenImage = createImage(getSize().width,getSize().height);
    • offscreenGraphics = offscreenImage.getGraphics();

HTML version of Basic Foils prepared Sept 21 1998

Foil 25 Double Buffering to Reduce Flicker - II

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
In paint(), one will construct applet image in offscreenGraphics as opposed to the argument g of paint(). So one would see statements such as:
  • offscreenGraphics.drawRect(x, y, w, h);
Finally at end of paint(), one could transfer the off-screen image to g by
  • g.drawImage(offscreenImage,0,0,this);
One would also need to override the update() method by
  • public void update(Graphics g)
  • { paint(g);
  • }

HTML version of Basic Foils prepared Sept 21 1998

Foil 26 Double Buffering

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index Movable Objects example with double buffering and boundary checking for Foil 26
The DigitalClock doesn't flicker, but this illustrates the technique on a short example.
public void class DigitalClock extends java.applet.Applet
implements Runnable
{ . . .
Image offscreenImg;
Graphics og;
public void init ( )
{ offscreenImg = createImage (getSize( ).width, getSize( ).height);
og = offscreenImg.getGraphics ( );
}
public void paint ( Graphics g )
{ og.setFont ( theFont );
og.drawString ( theDate.toString ( ), 10, 50 );
g.drawImage ( offscreenImg, 0, 0, this);
}
public void update ( Graphics g)
{ paint ( g); }
}

HTML version of Basic Foils prepared Sept 21 1998

Foil 27 Abstract Windowing Toolkit (AWT):

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
Components such as buttons, textfields, etc.
Java 1.1 Event Model

HTML version of Basic Foils prepared Sept 21 1998

Foil 28 AWT GUI Components

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
In Java, the GUI (Graphical User Interface) is built hierarchically in terms of Components -- one Component nested inside another starting with the smallest Buttons, including Menus, TextFields etc. and ending with full Window divided into Frames, MenuBars etc.
The placement of components in the window is controlled in a fairly high-level way by one of several Layout Managers.
The user can interact with the GUI on many of its components, by clicking a button, typing in text, etc. These actions cause an Event to be generated, which will be reported by the system to a class which is an Event Listener, and which will have an event handler method for that event. This method will provide the appropriate response to the user's action.

HTML version of Basic Foils prepared Sept 21 1998

Foil 29 Picture of the AWT Component Class and its inheritance

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
Other components can be placed inside a container.
Component
Label
Button
Checkbox
Scrollbar
TextComponent
TextArea
Textfield
ScrollPane
List
Canvas
Container
Panel
Window
Applet
Dialog
Frame

HTML version of Basic Foils prepared Sept 21 1998

Foil 30 Basic AWT Components

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
For each basic component, one can create one or more instances of the component type and then use one of the "add" methods to place it into a Container such as an applet window.
For now, we assume that components are added to the window in order from left to right and top to bottom as they fit. (This is actually the default FlowLayout Manager).
Also for each component, there will be other methods:
  • some affect the properties or appearance of the component, such as setBackground.
  • others may dynamically obtain or change information about the component, such as getText for TextFields, which may return whatever String the user has typed into the TextField.

HTML version of Basic Foils prepared Sept 21 1998

Foil 31 Basic AWT Component: Label

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index Labels for Foil 31
This is an area where text can be displayed in the window.
Create an instance of the Label class and add it to the window:
  • Label label1 = new Label ( "aligned left");
  • add (label1);
Another constructor allows a second argument which is an alignment: Label.LEFT, Label.CENTER, or Label.RIGHT
  • Label label2 = new Label ("aligned right", Label.RIGHT);
Method setText allows you to change the String in the Label, and getText() returns the current String
  • label2.setText("another message");
aligned left aligned right

HTML version of Basic Foils prepared Sept 21 1998

Foil 32 Basic AWT Component: Button

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index Buttons for Foil 32
A Button is the familiar way to allow a user to cause an event and is created with a String to label it
  • Button button1 = new Button("Click here");
  • add (button1);
Buttons are normally created to appear in the style of the user's windowing system, except that you can control the color of the button and the String
  • button1.setBackground (Color.cyan);
  • button1.setForeground (Color.black);
Click here

HTML version of Basic Foils prepared Sept 21 1998

Foil 33 The AWT Event Model

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
An Event Listener is an instance of any class that wants to receive events.
An event source is an object that generates events. An event source will keep a list of event listeners who want to be notified for particular events.
The event source notifies event listeners by invoking a particular method of the event listener (aka the event handler method) and passing it an Event object, which has all the information about the event.
For example, a component with a button is an event source, which generates an event called ActionEvent. There must be a class which implements an interface called ActionListener and which is on the list of listeners for that button. Then the Java system will provide the mechanism that passes the ActionEvent to a standard method of the ActionListener interface, namely a method called actionPerformed(). This method will receive the event object and carry out the response to the event.

HTML version of Basic Foils prepared Sept 21 1998

Foil 34 Setting up ActionEvents for a Button

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
When the button is created, it should have at least one listener class added to its list of listeners:
  • button1.addActionListener ( eventclass );
where eventclass is an instance of the listener class.
  • every component which can cause an event called X, has methods addXListener and removeXListener.
Then this class must implement the interface ActionListener. This interface requires only one event handler method:
  • public class EventClass implements ActionListener
  • {
  • public void actionPerformed ( ActionEvent e) { ... }
  • }
If the event source class is acting as its own listener, then you just say
  • button1.addActionListener ( this );

HTML version of Basic Foils prepared Sept 21 1998

Foil 35 The Event Classes

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index API for class Event
Every event has a source object, obtained by getSource(), and a type value, obtained by getID(). In the case of buttons, the ID is ACTION_PERFORMED. Other Events may have more than one type of event ID.
Event subclasses also have methods for whatever data is needed to handle the event. For example, ActionEvent has a method paramString() which for buttons, returns the string labelling the button. MouseEvent has methods getX() and getY(), which return the x and y pixel location of the mouse, and getClickCount().
AWTEvent
ActionEvent
InputEvent
Adjustment
Event
ItemEvent
ComponentEvent
MouseEvent
KeyEvent
. . .

HTML version of Basic Foils prepared Sept 21 1998

Foil 36 AWT Components -- Text Fields & Areas

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index TextFields and TextAreas for Foil 36
To add a text field for display or input one line of text (in this case, 30 characters wide):
  • TextField tf = new TextField("initial text", 30);
  • add(tf);
The text which is displayed can be changed:
  • tf.setText("now show a new text");
If the user types input into the text field, it can be obtained:
  • stringvar = tf.getText();
Or you can disallow the user to type:
  • tf.setEditable(false);
The TextArea class also has these methods, but it can display multiple lines.
When the user types in text and presses "return" or "enter", an ActionEvent is generated, so, similarly to Buttons, an ActionListener must be provided.

HTML version of Basic Foils prepared Sept 21 1998

Foil 37 AWT Components -- Checkbox

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index Checkboxes for Foil 37
Checkboxes are on-off toggles implemented as
  • Checkbox red = new Checkbox("Red");
  • Checkbox green = new Checkbox("Green");
  • Checkbox blue = new Checkbox("Blue",null, true);
  • add(red); add(green); add(blue);
The first two are initially set to "false" as the optional third argument is not given. The last one is initially set to "true".
The state of a checkbox, i.e. whether it is checked, is given by a boolean result of the method, getState:
  • if (red.getState()) . . .;
If a user clicks a Checkbox, an ItemEvent is generated. The listener must implement ItemListener with the one method itemStateChanged (ItemEvent e).
Red
Green
Blue

HTML version of Basic Foils prepared Sept 21 1998

Foil 38 AWT Components -- Radio Buttons , CheckboxGroup

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index  for Foil 38
Radio buttons are identical to Checkboxes but grouped so that only one checkbox in a group can be on at a time. They use same class for checkboxes, but add CheckboxGroup class.
  • CheckboxGroup cbg = new CheckboxGroup();
  • cb1 = new Checkbox("Red", cbg, false));
  • cb2 = new Checkbox("Green", cbg, false));
  • cb3 = new Checkbox("Blue", cbg, true));
  • add(cb1); add(cb2); add(cb3);
In addition to checking the state of checkboxes in a group, there is a method to return the one checkbox which is on:
  • cb = cbg.getSelectedCheckbox();

HTML version of Basic Foils prepared Sept 21 1998

Foil 39 Some Further AWT Components -- typical subunits of panels

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index The remaining basic Components for Foil 39
Choice is a class that gives a menu where you choose from various items, also sometimes called a drop-down list. Selecting an element of the menu generates an ItemEvent.
List is another child of Component that is similar in use to Choice but gives a fixed size list which can be scrolled and where you can select one or more entries. Lists can generate both ItemEvents if the user selects (clicks once) an item, and ActionEvents if the user double-clicks an item.
Scrollbar is a class that defines a horizontal or vertical scrollbar. Note this is distinct from scrollbars that come with TextArea and List. It generates AdjustmentEvents. The AdjustmentListener must have a method adjustmentValueChanged.

HTML version of Basic Foils prepared Sept 21 1998

Foil 40 Keyboard and Mouse Events

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index API for class KeyEvents
More generally, any component, including containers, can generate mouse and keyboard events as the user moves or clicks the mouse in the window, or types a single key on the keyboard.
This is most likely used in a Canvas or graphics drawing area.
Typing a single key generates two KeyEvents. These events must be handled by implementing the KeyListener interface. It has three methods corresponding to the three actions that can occur on a key:
  • public void keyPressed (KeyEvent e)
  • this is called for an action key, such as arrow keys, home, etc.
  • public void keyTyped (KeyEvent e)
  • this is called for other keys, such as text characters
  • public void keyReleased (KeyEvent e)
  • this is called when any key is released
Typically, one uses methods to find the name of the key pressed or typed:
  • String s = e.getKeyText (e.getKeyCode());

HTML version of Basic Foils prepared Sept 21 1998

Foil 41 Mouse Events

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index API for class MouseEvent
There are seven different MouseEvents, handled by methods in both the MouseListener and the MouseMotionListener interfaces.
  • MouseListener:
    • public void mousePressed (MouseEvent e)
      • called when the mouse button is pressed with the cursor in this component
    • public void mouseClicked (MouseEvent e)
      • called when the mouse button is pressed and released without moving the mouse
    • public void mouseReleased (MouseEvent e)
      • called when the mouse button is let up after dragging
    • public void mouseEntered (MouseEvent e)
      • called when the mouse cursor enters the bounds of the component
    • public void mouseExited (MouseEvent e)
      • called when the mouse cursor leaves the component
    • MouseMotionListener
      • public void mouseDragged (MouseEvent e)
      • called when the mouse is moved while the button is held down
      • public void mouseMoved (MouseEvent e)
      • called when the mouse cursor moves

HTML version of Basic Foils prepared Sept 21 1998

Foil 42 Using Mouse Events for User Interaction

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index MouseEvents examples for Foil 42
We set up a test program that creates three movable objects, a rectangle, circle and triangle, as in the earlier example. In this program, we start with them all red. Whenever the mouse is detected to be over one of the objects, its color is changed to cyan. If the mouse button is used to drag the object, we move the object to the mouse location.
Note that it is not necessary to introduce a thread for this applet since it is not running continuously - it is mostly waiting for mouse events.

HTML version of Basic Foils prepared Sept 21 1998

Foil 43 Separate Classes for Event Listeners

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
In designing classes for event handling, typically there is a class that defines the components where the response to the event is supposed to be performed. It is the most straightforward to make this class implement the listener for those events.
In large applications, some Java experts recommend that it is a better design to always make the event listener class a separate class. They find that they can make event listener classes generic enough so that they can reuse a class such as
  • public class ActionHandler implements ActionListener
  • to handle ActionEvents for many parts of the application.

HTML version of Basic Foils prepared Sept 21 1998

Foil 44 Adapter Classes

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index Adapter classes for Foil 44
For every Event Listener interface with more than one method, there is a corresponding Event Adapter class. For example, there is an MouseAdapter class to go with the MouseListener interface.
The adapter class implements its corresponding listener class by providing all of the required methods, but which have bodies that do nothing.
For interfaces like MouseListener and MouseMotionListener, this can be handy because there are several methods in each interface. Typically, you don't want to implement all of the methods. So it is more convenient to make a class which extends the adapter class than to directly implement the listener class.
  • class MouseHandler extends MouseAdapter
  • { ... // override only the methods that you want to implement
  • public void mousePressed(MouseEvent e) { . . . }
  • }

HTML version of Basic Foils prepared Sept 21 1998

Foil 45 Abstract Windowing Toolkit (AWT): Layouts

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index

HTML version of Basic Foils prepared Sept 21 1998

Foil 46 Layout of Components in a Panel

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
The various panels in a container are laid out separately in terms of their subcomponents
One can lay components out "by hand" with positioning in pixel space
However this is very difficult to make machine independent. Thus one tends to use general strategies which are embodied in 5 LayoutMangers which all implement the LayoutManager Interface. One can expect further custom LayoutManager's to become available on the Web
To create a layout, such as FlowLayout, in your panel:
  • setLayout(new FlowLayout());
  • This particular Layout is the default.

HTML version of Basic Foils prepared Sept 21 1998

Foil 47 Brief Description of LayoutManagers

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index
FlowLayout is a one dimensional layout where components are "flowed" into panel in order they were defined. When a row is full up, it is wrapped onto next row
BorderLayout arranges the components into five areas called North, South, East, West and Center.
GridLayout is a two dimensional layout where you define a N by M set of cells and again the components are assigned sequentially to cells starting at top left hand corner -- one component is in each cell. The cells are the same size.
CardLayout lays out in time not space and each card (Displayed at one time) can be laid out with one of spatial layout schemes above
GridBagLayout uses a class GridBagConstraints to customize positioning of individual components in one or more cells

HTML version of Basic Foils prepared Sept 21 1998

Foil 48 Description and Example of BorderLayout

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index BorderLayouts for Foil 48
BorderLayout has five cells called North South East West Center and components are assigned to these cells with the add method. Unlike other add methods, here the order is not important:
  • add(new TextField("Title",50), BorderLayout.NORTH);
  • add(new TextField("Usually_status_message",50), BorderLayout.SOUTH);
Remember this is default for a Frame Container
The constructor "new BorderLayout()" can have no arguments or "new BorderLayout(hgap, vgap)" can specify numbers of pixels inbetween components.
North
South
W
e
s
t
E
e
s
t

HTML version of Basic Foils prepared Sept 21 1998

Foil 49 FlowLayouts in detail

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index API for class FlowLayout
This simple layout manager "flows" components into the window. The components can be aligned, and space between them specified by arguments hgap and vgap:
  • setLayout(new FlowLayout(FlowLayout.LEFT, 5, 2)); setLayout(new FlowLayout(FlowLayout.CENTER));
  • setLayout(new FlowLayout(FlowLayout.RIGHT));
The FlowLayout Manager's strategy includes making each component its default "preferred size".

HTML version of Basic Foils prepared Sept 21 1998

Foil 50 GridLayouts

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index GridLayouts for Foil 50
The first two arguments of the GridLayout constructor specify the number of rows of cells (i.e. number of cells in the y direction) and the number of columns of cells (in the x direction)
  • setLayout(new GridLayout (2, 3));
Additional arguments hgap and vgap specify the number of pixels inbetween the columns and rows:
  • setLayout(new GridLayout (2, 3, 10, 15 ));
The GridLayout Manager's strategy is to make each cell exactly the same size so that rows and columns line up in a regular grid.

HTML version of Basic Foils prepared Sept 21 1998

Foil 51 Hierarchical Use of Layouts

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index More Layout examples for Foil 51
Each component in a Layout may itself be a Panel with another Layout Manager, thus subdividing areas of the user interface. Using this hierarchy one can achieve complex GUI's.
A simple example of using hierarchical Layout divides the main applet space into two components in a BorderLayout. The Center component is a Canvas for drawing graphics or images; the North component is itself a Panel which has three buttons in a GridLayout. This example is a very simple example of a standard paradigm for drawing or displaying data.
  • Also note other examples showing CardLayouts and GridBagLayouts.

HTML version of Basic Foils prepared Sept 21 1998

Foil 52 Abstract Windowing Toolkit (AWT): More Components

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index

HTML version of Basic Foils prepared Sept 21 1998

Foil 53 AWT Component: Canvas

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index API for class Canvas
Canvas is a simple class that is used to draw on as in artist's canvas. They cannot contain other components. This is the class on which you use the graphics methods.
Canvases can be included as parts of other Containers. In this case, you may need to obtain a Graphics object for drawing:
  • Canvas drawcanvas;
  • Graphics drawgraphics = drawcanvas.getGraphics();
    • drawgraphics.drawString("Graph Label");

HTML version of Basic Foils prepared Sept 21 1998

Foil 54 Some Further AWT Components: Window (Frame and Dialog)

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index Window and Frame for Foil 54
Up to now, we have described how to build typical Applet panels inside browser window. There are classes that allow one to generate complete windows separately from the browser window
Window Class has subclasses Frame and Dialog
Create a window with a given title:
  • Frame f = new Frame("TitleofWindow");
  • Frames appear and disappear by using the method setVisible:
    • f.setVisible(true); // makes the window appear on the screen
    • f.setVisible(false); // makes the window disappear from the screen
  • Note Frame is a Container and can thereof be defined hierarchically with components that are laid out by LayoutManagers
  • Note a Frame in Java is NOT THE SAME as a frame in HTML

HTML version of Basic Foils prepared Sept 21 1998

Foil 55 Frames can have MenuBars

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index classes for menus in frames for Foil 55
A Frame has a set of classes to define MenuBars and Menus:
  • Menubar mbar = new MenuBar(); // defines a menubar which can be used in a frame
Several Menus, which each have menu items, can be added to the menubar:
  • Menu typeMenu = new Menu("Type");
  • typeMenu.add(new MenuItem("Black/White"));
  • typeMenu.add(new MenuItem("Color"));
  • typeMenu.addSeparator();
  • MenuItem q = new MenuItem("Quit"); q.addActionListener;
  • typeMenu.add ( q );
  • mbar.add(typeMenu);
  • When the user selects an item on a menu, an ActionEvent is reported to the ActionListener, where it can be handled
    • public void actionPerformed(ActionEvent e)
    • { if (e.getSource() == q)
    • { q.setVisible(false); } }
Note that there are also CheckboxMenuItems, submenus,and (new) MenuShortcuts.

HTML version of Basic Foils prepared Sept 21 1998

Foil 56 Dialog Boxes

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index API for class Dialog
Another type of separate window is the Dialog box, which is not so elaborate as a frame.
  • Dialog(Frame, String Title, boolean mustbeansweredatonceornot);
  • // defines a dialog box
Dialog boxes are used for transient data
  • Issue warning to user or require (third argument true) user to verify some action etc. - e.g. this dialog box has warning text and an ok button:
    • class WarningDialog extends Dialog
    • { public WarningDialog(Frame parent)
    • {super(parent, "Dialog Box Label", true); //modal requires immediate
    • add(new Label("Read this stern Warning!"));
    • Button b = new Button("OK"));
    • b.addActionListener(this); add(b);
    • setSize(200,100); }
    • public void actionPerformed(ActionEvent e)
    • {if (e.getActionCommand().equals("OK")) dispose();
    • }
    • }

HTML version of Basic Foils prepared Sept 21 1998

Foil 57 New Components: ScrollPanes and PopupMenus

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index new component classes for Foil 57
A ScrollPane provides a scrollable area within an existing window. It is a container which can have one other component added to it. This component may have a larger area that will be visible in the ScrollPane. For example, suppose that you have a Canvas drawing area that is 1000 by 1000 pixels wide. You can define a ScrollPane that will view part of it at one time.
  • Canvas draw = new Canvas();
  • draw.setSize (1000, 1000);
  • ScrollPane drawscroller = new ScrollPane();
  • drawscroller.add (draw);
  • drawscroller.setSize (250, 250);
  • add(drawscroller);
A PopupMenu is a sometimes called a context-sensitive menu. On most systems, the right mouse button cause a popup trigger event, and you can create a PopupMenu to appear.

HTML version of Basic Foils prepared Sept 21 1998

Foil 58 PPT Slide

From Java Tutorial 98- 3: Graphics and the Abstract Windowing Toolkit NAVO Tutorial -- Sept 23 1998. *
Full HTML Index

© Northeast Parallel Architectures Center, Syracuse University, npac@npac.syr.edu

If you have any comments about this server, send e-mail to webmaster@npac.syr.edu.

Page produced by wwwfoil on Sat Nov 28 1998