Full HTML for

Basic foilset Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract Windowing Toolkit

Given by Nancy J. McCracken,Geoffrey C. Fox at CEWES Tutorial on July 22-25 1997. Foils prepared 19 July 97
Outside Index Summary of Material


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 - Summer 1997 Part 3:Graphics and the Abstract Windowing Toolkit

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

1 Java Tutorial -
Spring 1997
Part 3: Graphics and the Abstract Windowing Toolkit
http://www.npac.syr.edu/projects/tutorials/Java/

2 More Detail on Applets and Graphics
3 The java.awt.Graphics Class
4 Graphics is Event-Driven: paint method
5 Changing Graphics: repaint method
6 The java.awt.Font and FontMetrics Classes
7 Centering a string in the applet window.
8 The java.awt.Color Classes
9 Introducing a Single Thread
(See later for real discussion of thread use)

10 Introduction to Threads
11 Example showing the standard thread methods
12 Example showing thread methods, continued
13 Images
and Double Buffering

14 Getting Images Downloaded
15 Drawing Images to the applet window
16 Image Downloading -- imageObserver, MediaTracker
17 An Image Drawing Example
18 Flickering in Applets and its Solution
19 The default Update(Graphics g) Method
20 Double Buffering to Reduce Flicker - I
21 Double Buffering to Reduce Flicker - II
22 Double Buffering
23 Event Handling
using the JDK 1.0 Event Model

24 Events in the java.awt -- Mouse, Keyboard Interaction - I
25 Events in the java.awt -- Mouse, Keyboard Interaction - II
26 Using Mouse Events for User Interaction
27 Mouse Events: Initializing the movable objects
28 Draw the objects with double buffering
29 Mouse Move Event
30 The Set of Mouse Dragging Events
31 More Methods in the Movable Point class
32 Keyboard Events
33 Abstract Windowing Toolkit (AWT):
Components such as buttons, textfields, etc.
and related Events

34 Structure of the java.awt GUI Components - I
35 Structure of the java.awt GUI Components - II
36 Picture of the AWT Component Class and its inheritance
37 Some Simple AWT Components -- label,button
38 AWT Components -- Checkbox
39 AWT Components -- Radio Buttons , CheckboxGroup
40 Actions associated with Components in AWT - I
41 Actions associated with Components in AWT - II
42 A more general way to handle events
43 Some Further AWT Components -- typical subunits of panels
44 AWT Components -- Text Fields & Areas
45 Some Further AWT Components -- Canvas, Window (Frame and Dialog)
46 Frames can have MenuBars
47 Dialog Boxes
48 Abstract Windowing Toolkit (AWT):
Layouts

49 Layout of Components in a Panel
50 Description and Example of BorderLayout
51 Brief Description of Four Other LayoutManager's
52 FlowLayouts in detail
53 Hierarchical use of LayoutManagers
54 AWT - Grid Layout with Two Components
55 AWT - Adding Components to a Layout
56 AWT - Canvas Component
57 AWT - Panel Component with Buttons
58 AWT - Handling Actions from Components

Outside Index Summary of Material



HTML version of Basic Foils prepared 19 July 97

Foil 1 Java Tutorial -
Spring 1997
Part 3: Graphics and the Abstract Windowing Toolkit
http://www.npac.syr.edu/projects/tutorials/Java/

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
Instructors: Geoffrey Fox ,
Nancy McCracken
Syracuse University
111 College Place
Syracuse
New York 13244-4100

HTML version of Basic Foils prepared 19 July 97

Foil 2 More Detail on Applets and Graphics

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index

HTML version of Basic Foils prepared 19 July 97

Foil 3 The java.awt.Graphics Class

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
java.awt has several important classes including Graphics, Color, Font and FontMetrics
Graphics class has primitives to construct basic two dimensional images with methods
drawString (text), drawLine,
drawArc, fillArc, drawRect, fillRect, drawOval, fillOval, drawRoundRect (for a rectangle with rounded corners!), draw3DRect (to get shadow effect as in buttons), drawPolygon (general polygon) (and fill versions of last 3)
There are also Image, Font, Color operations

HTML version of Basic Foils prepared 19 July 97

Foil 4 Graphics is Event-Driven: paint method

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
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:
  • void paint(Graphics g)
In this method you put everything you want to draw in the window. The Graphics object g has things like a current color and current font, and there are methods for you to change these as well as draw.
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 a method called update, which blanks the screen and then calls paint(g). So even if you only draw one window, paint can be called many times.

HTML version of Basic Foils prepared 19 July 97

Foil 5 Changing Graphics: repaint method

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
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
  • void repaint();
Repaint gets the graphics context and creates a thread to call update, which calls your paint function. So all your drawing changes can also be put into 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 19 July 97

Foil 6 The java.awt.Font and FontMetrics Classes

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
Graphicsinstance.setFont(particularFont) will set the current Font in the instance Graphicsinstance of graphics class to the value particularFont of class Font. There are several other such Font related methods in the Graphics class
The class Font has an important constructor used as in
Font MyFont = new Font("TimesRoman", Font.PLAIN ,36);
  • where one can use Courier Helvetica etc. instead of TimesRoman
  • 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 one line of Font
  • getAscent(), getDescent(), getLeading(), getMaxAscent(), getMaxDescent()

HTML version of Basic Foils prepared 19 July 97

Foil 7 Centering a string in the applet window.

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
The method applet.size() returns a dimension object, which has width and height variables. FontMetrics has variables for various attributes of the font, including width and height.

HTML version of Basic Foils prepared 19 July 97

Foil 8 The java.awt.Color Classes

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
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
graphicsobject.setFont(particularFont); // similarily sets font hereafter as on previous page
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)

HTML version of Basic Foils prepared 19 July 97

Foil 9 Introducing a Single Thread
(See later for real discussion of thread use)

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index

HTML version of Basic Foils prepared 19 July 97

Foil 10 Introduction to Threads

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
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 which 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, which is almost always recommended:
  • 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 which creates a thread and starts it running and a stop() method which stops it running.
  • Have a run() method containing the body of your applet code.

HTML version of Basic Foils prepared 19 July 97

Foil 11 Example showing the standard thread methods

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
These applet start and stop methods can always be used to start and stop the thread.

HTML version of Basic Foils prepared 19 July 97

Foil 12 Example showing thread methods, continued

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
The body of the applet is in the run method, in this case a loop to keep showing the date.

HTML version of Basic Foils prepared 19 July 97

Foil 13 Images
and Double Buffering

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index

HTML version of Basic Foils prepared 19 July 97

Foil 14 Getting Images Downloaded

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
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 19 July 97

Foil 15 Drawing Images to the applet window

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
The Graphics class provides a method drawImage to actually display the image on the browser screen.
You can also scale the image to a particular width and height.

HTML version of Basic Foils prepared 19 July 97

Foil 16 Image Downloading -- imageObserver, MediaTracker

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
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 which call paint and drawImage, so that more of the image should 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 which can 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 19 July 97

Foil 17 An Image Drawing Example

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
This example shows how to get the actual height and width of the image to use in scaling the image under java program control.

HTML version of Basic Foils prepared 19 July 97

Foil 18 Flickering in Applets and its Solution

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
Unless you are careful, dynamic applets will give flickering screens
This is due to cycle
paint(g)
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 19 July 97

Foil 19 The default Update(Graphics g) Method

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
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,width,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 19 July 97

Foil 20 Double Buffering to Reduce Flicker - I

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
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(width,height);
  • offscreenGraphics = offscreenImage.getGraphics();

HTML version of Basic Foils prepared 19 July 97

Foil 21 Double Buffering to Reduce Flicker - II

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
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.drawImage(img,10,10,this);
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 19 July 97

Foil 22 Double Buffering

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
This technique is most effective in eliminating flicker, but does take longer and use more memory.

HTML version of Basic Foils prepared 19 July 97

Foil 23 Event Handling
using the JDK 1.0 Event Model

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index

HTML version of Basic Foils prepared 19 July 97

Foil 24 Events in the java.awt -- Mouse, Keyboard Interaction - I

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
Events ( distinguish these from Exceptions!) are the way the AWT interacts with the user at mouse or keyboard.
The AWT calls particular event handlers (analogous to exception or interrupt handlers) when user interacts with system in particular ways.
The handling is defined in packages java.awt and java.awt.peer (the machine dependent stuff) with method handleEvent() in class Component(peer)
One could add additional capability here for systems with nifty virtual reality and other user interfaces but we won't cover this here!

HTML version of Basic Foils prepared 19 July 97

Foil 25 Events in the java.awt -- Mouse, Keyboard Interaction - II

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
The Event class has various special class (static) variables defined including
  • Event.F1 -- the F1 key
  • Event.UP The Up arrow etc.
The Component class (grandparent of Applet) has a rich set of Event handlers which you should override if you wish to process particular input. In this section, we cover the keyboard and mouse events which are reported to subclass Canvas (used for Graphics)
public boolean mouseDown(Event evt, int x, int y) {
  • anchor = new Point(x,y); // record position of mouse click
  • return true; // must do this
  • }
Other handlers are mouseDrag, mouseEnter (enters current component), mouseExit, mouseMove (with its button up), keyUp, keyDown

HTML version of Basic Foils prepared 19 July 97

Foil 26 Using Mouse Events for User Interaction

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
We set up a test program that creates 3 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 19 July 97

Foil 27 Mouse Events: Initializing the movable objects

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index

HTML version of Basic Foils prepared 19 July 97

Foil 28 Draw the objects with double buffering

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
In this example, update does all the drawing. It also sets a background color rectangle with a 1 pixel border in the foreground color.

HTML version of Basic Foils prepared 19 July 97

Foil 29 Mouse Move Event

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
Whenever the user moves the mouse, a message is sent from the client workstation to the Java system. It generates a form of interrupt called an event. Your Java applet can choose to provide a method which does appropriate response for any event. This is called an event handler - you must return true to show the general event handler that you have intervened.

HTML version of Basic Foils prepared 19 July 97

Foil 30 The Set of Mouse Dragging Events

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
These handle the sequence of: the user clicks the mouse (mouse down), moves the mouse (mouse drag) and releases the mouse button (mouse up).

HTML version of Basic Foils prepared 19 July 97

Foil 31 More Methods in the Movable Point class

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
We add methods to detect when the mouse is inside an object, and a more general method moveTo for large moves under dragging.

HTML version of Basic Foils prepared 19 July 97

Foil 32 Keyboard Events

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
You may also choose to respond to individual keys being pressed from the keyboard. (Later we will learn of a more general way to handle text input.)

HTML version of Basic Foils prepared 19 July 97

Foil 33 Abstract Windowing Toolkit (AWT):
Components such as buttons, textfields, etc.
and related Events

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index

HTML version of Basic Foils prepared 19 July 97

Foil 34 Structure of the java.awt GUI Components - I

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
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.
Not all useful Classes are inherited from Component. For instance Menu inherits from MenuComponent (interface) --> MenuItem --> Menu
One also needs a set of methods and classes to define the layout of the Components in a particular Panel
LayoutManager is a java.awt interface with several particular layout strategies implemented as classes under this interface
The Container class has methods to interact with LayoutManager classes

HTML version of Basic Foils prepared 19 July 97

Foil 35 Structure of the java.awt GUI Components - II

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
In the simplest use of AWT, one could add a Button to an Applet (grandchild of Container) using in the init() method for Applet
  • Button b = new Button("Are You Feeling well");
  • add(b); // add() is a Container method
The various added Components are put in the panel by the LayoutManager using order in which they were added
A Final critical part of the AWT is the actions generated by these components which are processed by overriding the action() method in Component
  • action(Event e, Object Anyargemightliketoreturn);
We define extra events -- such as those connected with scrolling or selecting buttons to those of basic mouse/keyboard

HTML version of Basic Foils prepared 19 July 97

Foil 36 Picture of the AWT Component Class and its inheritance

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
This is incomplete!

HTML version of Basic Foils prepared 19 July 97

Foil 37 Some Simple AWT Components -- label,button

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
add(new Label("aligned left")); // default alignment
produces a text string using constructor Label of Label class
add(new Button("Grade is A"));
add(new Button("Grade is B")); // surely this is lowest grade for a course on such an easy language?

HTML version of Basic Foils prepared 19 July 97

Foil 38 AWT Components -- Checkbox

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
Checkbox's are on-off toggles implemented as
add(new Checkbox("Red"));
add(new Checkbox("Green"));
add(new Checkbox("Blue"),null, true);
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 the method, getState:
Checkbox cb = new Checkbox("Red");
add (cb);
. . .
if (cb.getState()) . . .;

HTML version of Basic Foils prepared 19 July 97

Foil 39 AWT Components -- Radio Buttons , CheckboxGroup

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
Radio buttons are identical to Checkbox's but grouped so that only one checkbox in a group can be on at a time. They use same class for buttons 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, the method getCurrent returns the one checkbox which is on:
  • cb = cbg.getCurrent();

HTML version of Basic Foils prepared 19 July 97

Foil 40 Actions associated with Components in AWT - I

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
We already discussed handling Mouse and Keyboard Events. These AWT components come with new actions which need to be handled with an action() method in your applet (and a few events which are reported directly to handlevent().)
Put action ( a method of class Component) in Container instance that is at lowest possible level so you can customize action to things in that Container
action(Event evt, Object arg)'s are looked for in same fashion as exceptions. Scan up Containers looking for a method of this name. Scanning stops when you find an action and that method returns true
evt.target holds the object that caused the Event
Object Arg returned depends on particular Component invoked
There are further evt.id's associated with the various peculiar Components -- see description of class Event for current detailed description.

HTML version of Basic Foils prepared 19 July 97

Foil 41 Actions associated with Components in AWT - II

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
Suppose we have a bunch of buttons in a particular Container saying Red, Green, Blue as we illustrated earlier. Then an action method would be
  • public boolean action(Event evt, Object arg) {
  • if( evt.target instanceof Button)
    • changeColor((String) arg);
    • // where changeColor is a method supplied by the user
  • return true; // tell runtime that this event fully processed
  • }
  • void changeColor(String bname) { // suitable user method
  • if( bname.equals("Red")) setBackground(Color.red);
    • else if (bname.equals("Green")) setBackground(Color.green);
    • else if (bname.equals("Blue")) setBackground(Color.blue);
    • else setBackground(Color.pink); // our favorite color
  • }

HTML version of Basic Foils prepared 19 July 97

Foil 42 A more general way to handle events

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
In general, declare names for all components such as labels, buttons and textfields, and use the variable evt.target to distinguish which component generated the action.

HTML version of Basic Foils prepared 19 July 97

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

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
Choice is a class that gives a menu where you choose from various items
TextField is a simple class where user can enter information into fields (more details on next page)
TextArea is a somewhat more sophisticated text entry area which are scrollable and so useful where amount of data to be entered is unlimited
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
Scrollbar is a class that defines a horizontal or vertical scrollbar. Note this is distinct from scrollbars that come with TextArea and List

HTML version of Basic Foils prepared 19 July 97

Foil 44 AWT Components -- Text Fields & Areas

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
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 can type 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.

HTML version of Basic Foils prepared 19 July 97

Foil 45 Some Further AWT Components -- Canvas, Window (Frame and Dialog)

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
Canvas is a simple class which are 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.
Upto 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
Frame("TitleofWindow"); // creates a window with given title
  • Frames appear and disappear by using methods show() and hide().
  • 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 Netscape 2.0 and higher

HTML version of Basic Foils prepared 19 July 97

Foil 46 Frames can have MenuBars

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
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();
  • typeMenu.add(new MenuItem("Quit");
  • mbar.add(typeMenu);
  • When the user selects an item on a menu, an event is reported to the action method, where it can be handled
  • public boolean action(Event evt, Object arg)
  • { if (evt.target instanceof MenuItem)
    • { if (arg.equals("Quit")) { hide(); }
    • } ... }

HTML version of Basic Foils prepared 19 July 97

Foil 47 Dialog Boxes

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
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!"));
    • add(new Button("OK"));
    • resize(200,100); }
  • public boolean action(Event evt, Object arg)
    • {if (arg.equals("OK")) { dispose(); return true;}
    • return false; }
  • }

HTML version of Basic Foils prepared 19 July 97

Foil 48 Abstract Windowing Toolkit (AWT):
Layouts

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index

HTML version of Basic Foils prepared 19 July 97

Foil 49 Layout of Components in a Panel

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
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
setLayout(new FlowLayout()); // creates a basic flow layout in your panel -- actually unnecessary as default
Other available LayoutManager's are GridLayout(), BorderLayout() (default for Frame's), CardLayout() (Used for dynamic layouts) and GridBagLayout() (the most flexible)

HTML version of Basic Foils prepared 19 July 97

Foil 50 Description and Example of BorderLayout

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
BorderLayout has five cells called North South East West Center and components are assigned to these cells with the add method. As used in a window, one would naturally use:
  • add("North", new TextField("Title",50));
  • add("South", new TextField("Usuallyreservedforstatusmessage",50));
Remember this is default for a Frame Container

HTML version of Basic Foils prepared 19 July 97

Foil 51 Brief Description of Four Other LayoutManager's

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
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
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
GridBagLayout uses a new class GridBagConstraints to customize positioning of individual components in one or more cells
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

HTML version of Basic Foils prepared 19 July 97

Foil 52 FlowLayouts in detail

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
This simple layout manager starts putting components in the window from the top left, continues across the row until there is no more room, starts the next row, and so on. The components can be aligned, and space between them given by the arguments hgap and vgap.
setLayout(new FlowLayout(FlowLayout.LEFT, 5, 1);
setLayout(new FlowLayout(FlowLayout.CENTER);
setLayout(new FlowLayout(FlowLayout.RIGHT);

HTML version of Basic Foils prepared 19 July 97

Foil 53 Hierarchical use of LayoutManagers

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
Layout's can be made very sophisticated using an hierarchical approach
setLayout(new GridLayout(1,3,10,5));
  • // Number of cells in y, Number in x, Horizontal gap, Vertical Gap
subpanel1 = new MysubpanelClass(); // Add arguments to make subpanel1 special
subpanel2 = new MysubpanelClass();
add(Some Simple Component such as a Button);
add(subpanel1);
add(subpanel2);
. . . . .
Class MysubpanelClass extends panel { // has constructor
MysubpanelClass() { // that includes another layout such as
setLayout(new GridLayout(2,2,5,5); // etc.

HTML version of Basic Foils prepared 19 July 97

Foil 54 AWT - Grid Layout with Two Components

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
A simple example of using the Abstract Windowing Toolkit divides the applet space into two components. One is a Canvas for drawing graphics or images; one is a Panel which has three buttons. We choose to draw the Canvas within the Applet and to create the Panel in another class.

HTML version of Basic Foils prepared 19 July 97

Foil 55 AWT - Adding Components to a Layout

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
At top level, the panel is divided into two components.

HTML version of Basic Foils prepared 19 July 97

Foil 56 AWT - Canvas Component

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
The initialization of the Canvas was done in the applet init method; the other method for painting the Canvas simply changes the background color. About the only thing a Canvas can do is explicit drawing and graphics.

HTML version of Basic Foils prepared 19 July 97

Foil 57 AWT - Panel Component with Buttons

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
This class does not need to be a subclass of Applet - like all components except Canvas, you don't need to paint, just add components and handle events and actions.

HTML version of Basic Foils prepared 19 July 97

Foil 58 AWT - Handling Actions from Components

From Java Tutorial - Summer 1997 Part 3:Graphics and the Abstract CEWES Tutorial -- July 22-25 1997. *
Full HTML Index
The Button component generates an action whenever the button is clicked on. In this example, we call the method that changes the color of the Canvas in another part of the layout.

© 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 Sun Oct 12 1997