Full HTML for

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

Given by Nancy J. McCracken,Geoffrey C. Fox at Peking Tutorial, Web Certificate on Spring-Summer 1997. Foils prepared 18 May 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 - Spring 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 Some Basic Methods for Applets -- I
7 Some Basic Methods for Applets -- II
8 The java.awt.Font and FontMetrics Classes
9 Centering a string in the applet window.
10 The java.awt.Color Classes
11 A Simple Useful Applet from Sun for Animation
(can be skipped)

12 Sun's Animator.class Applet
13 Details of Using the Sun animator Applet --I
14 Details of Using the Sun animator Applet --II
15 Introducing a Single Thread
(See later for real discussion of thread use)

16 Introduction to Threads
17 Example showing the standard thread methods
18 Example showing thread methods, continued
19 Images
and Double Buffering

20 Getting Images Downloaded
21 Drawing Images to the applet window
22 Image Downloading -- imageObserver, MediaTracker
23 An Image Drawing Example
24 Flickering in Applets and its Solution
25 The default Update(Graphics g) Method
26 Double Buffering to Reduce Flicker - I
27 Double Buffering to Reduce Flicker - II
28 Double Buffering
29 Event Handling
30 Events in the java.awt -- Mouse, Keyboard Interaction - I
31 Events in the java.awt -- Mouse, Keyboard Interaction - II
32 Using Mouse Events for User Interaction
33 Mouse Events: Initializing the movable objects
34 Draw the objects with double buffering
35 Mouse Move Event
36 The Set of Mouse Dragging Events
37 More Methods in the Movable Point class
38 Keyboard Events
39 Abstract Windowing Toolkit (AWT):
Components such as buttons, textfields, etc.
and related Events

40 Structure of the java.awt GUI Components - I
41 Structure of the java.awt GUI Components - II
42 Picture of the AWT Component Class and its inheritance
43 Some Simple AWT Components -- label,button
44 AWT Components -- Checkbox
45 AWT Components -- Radio Buttons , CheckboxGroup
46 Actions associated with Components in AWT - I
47 Actions associated with Components in AWT - II
48 A more general way to handle events
49 Some Further AWT Components -- typical subunits of panels
50 AWT Components -- Text Fields & Areas
51 Some Further AWT Components -- Canvas, Window - I
52 Some Further AWT Components -- Canvas, Window - II
53 Abstract Windowing Toolkit (AWT):
Layouts

54 Layout of Components in a Panel
55 Description and Example of BorderLayout
56 Brief Description of Four Other LayoutManager's
57 FlowLayouts in detail
58 Hierarchical use of LayoutManagers
59 AWT - Grid Layout with Two Components
60 AWT - Adding Components to a Layout
61 AWT - Canvas Component
62 AWT - Handling Actions from Components
63 AWT - Panel Component with Buttons

Outside Index Summary of Material



HTML version of Basic Foils prepared 18 May 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 - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 2 More Detail on Applets and Graphics

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index

HTML version of Basic Foils prepared 18 May 97

Foil 3 The java.awt.Graphics Class

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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, drawRect, fillRect, drawRoundRect (for a rectangle with rounded corners!), draw3DRect (to get shadow effect as in buttons), drawPolygon (general polygon), drawOval, fillOval
There are also Image, Font, Color operations

HTML version of Basic Foils prepared 18 May 97

Foil 4 Graphics is Event-Driven: paint method

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 5 Changing Graphics: repaint method

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 6 Some Basic Methods for Applets -- I

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index
Some of These are in Applet and some in parent (in particular Component)
public void init() is called ONCE and ONCE only when the applet is loaded or reloaded. Set initial parameters etc. here.
public void destroy() is what you do when Applet is entirely finished and you need to clean up stray threads or connections to be closed.
public void start() is called whenever the applet is started which can happen several times during an applet's life-cycle as it starts each time you revisit a page
public void stop() is called when we temporarily leave Applet to visit another page. A wise move would be to suspend running of Threads to save system resources.

HTML version of Basic Foils prepared 18 May 97

Foil 7 Some Basic Methods for Applets -- II

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index
public void paint(Graphics g) actually has an argument and draws what you want on the screen
There is somewhat confusing other methods update() and repaint() which need to used in advanced applications. You may need to call repaint() in a dynamic applet to change display but update() would not need to be called as invoked by repaint(). However update() is sometimes best overridden
public void repaint() is a request by you to the Java runtime to update screen
public void update(Graphics g) is invoked by repaint() and performs the screen update which involves clearing screen and invoking paint()

HTML version of Basic Foils prepared 18 May 97

Foil 8 The java.awt.Font and FontMetrics Classes

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 particularFont = new Font("TimesRoman",Font.PLAIN,36);
where one can use Courier Helvetica etc. instead of Time Roman
Font.PLAIN, Font.BOLD, Font.ITALIC are possible text styles
FontMetrics fm = getFontMetrics(particularFont); // allows one to find out about the font, such as leading, aspect, etc.
fm.stringWidth("text"); // returns pixel width of string "text"
fm.getHeight(); // returns total height of one line of Font

HTML version of Basic Foils prepared 18 May 97

Foil 9 Centering a string in the applet window.

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 10 The java.awt.Color Classes

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 11 A Simple Useful Applet from Sun for Animation
(can be skipped)

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index

HTML version of Basic Foils prepared 18 May 97

Foil 12 Sun's Animator.class Applet

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index
Sun distributes a general purpose Animation applet with the Java Development Kit
Advantages:
  • 1. quick: users don't have to write their own program in order to get interesting animation effects.
  • 2. flexibility: user can assign the directory and the file name for the image frame and sound files by using imagesource, soundsource, soundtrack, and sound parameters in applet tag.
Disadvantages:
  • 1. Image blinking: This applet fails to use double buffering and one can see serious blinking on screen.
  • 2. Separating the frames into different files makes it easy to program but will slow down the image loading process.

HTML version of Basic Foils prepared 18 May 97

Foil 13 Details of Using the Sun animator Applet --I

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index
1. Prepare a directory. and cd to this directory.
2. Copy Animator.class, ParseException.class, and ImageNotFoundException.class into your directory.
3. create a directory audio and put your audio file in it.
Your audio files can be called 0.au, 1.au, etc.
  • The background soundtrack could be any .au file.
4. create a directory images and put your image files in it.
  • your image files can be called T1.gif, T2.gif, etc.
  • the loading message can be called loading-msg.gif.
5. prepare a HTML page which has the following type of applet tag:
<applet code=Animator.class width=200 height=200>
<param name=imagesource value="images">
<param name=endimage value=10>
<param name=soundsource value="audio">
<param name=soundtrack value=spacemusic.au>
<param name=sounds value="1.au|2.au|3.au|4.au|5.au|6.au|7.au|8.au|9.au|0.au">
<param name=pause value=200>
</applet>

HTML version of Basic Foils prepared 18 May 97

Foil 14 Details of Using the Sun animator Applet --II

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index
the imagesource attribute indicate you put your image files in directory images.
the endimage value 10 indicate that you have 10 image files held in
  • T1.gif, T2.gif, ..., to T10.gif
The soundsource indicate that you put your sound files in audio directory.
The sounds attribute lets you express your audio file sequence.
the pause attribute is the pause (ms) between each image frame.
There are other parameters which can be set such as:
<param name=startup value="loading-msg.gif">
This image will show up first to remind user that image is loading.

HTML version of Basic Foils prepared 18 May 97

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

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index

HTML version of Basic Foils prepared 18 May 97

Foil 16 Introduction to Threads

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 17 Example showing the standard thread methods

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index
These start and stop methods can always be used

HTML version of Basic Foils prepared 18 May 97

Foil 18 Example showing thread methods, continued

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 19 Images
and Double Buffering

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index

HTML version of Basic Foils prepared 18 May 97

Foil 20 Getting Images Downloaded

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 21 Drawing Images to the applet window

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 22 Image Downloading -- imageObserver, MediaTracker

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 23 An Image Drawing Example

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 24 Flickering in Applets and its Solution

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 25 The default Update(Graphics g) Method

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 26 Double Buffering to Reduce Flicker - I

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 27 Double Buffering to Reduce Flicker - II

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 28 Double Buffering

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 29 Event Handling

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index

HTML version of Basic Foils prepared 18 May 97

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

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

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

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 32 Using Mouse Events for User Interaction

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 33 Mouse Events: Initializing the movable objects

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index

HTML version of Basic Foils prepared 18 May 97

Foil 34 Draw the objects with double buffering

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 35 Mouse Move Event

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 36 The Set of Mouse Dragging Events

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 37 More Methods in the Movable Point class

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 38 Keyboard Events

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

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

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index

HTML version of Basic Foils prepared 18 May 97

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

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

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

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 42 Picture of the AWT Component Class and its inheritance

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index
This is incomplete!

HTML version of Basic Foils prepared 18 May 97

Foil 43 Some Simple AWT Components -- label,button

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 44 AWT Components -- Checkbox

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 45 AWT Components -- Radio Buttons , CheckboxGroup

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index
Radiobuttons 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 18 May 97

Foil 46 Actions associated with Components in AWT - I

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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
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 18 May 97

Foil 47 Actions associated with Components in AWT - II

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 48 A more general way to handle events

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

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

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 50 AWT Components -- Text Fields & Areas

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 51 Some Further AWT Components -- Canvas, Window - I

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 memubar and given title
  • 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 18 May 97

Foil 52 Some Further AWT Components -- Canvas, Window - II

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index
A Frame has a set of classes to define MenuBars and Menus:
  • MenuBar(); // defines a menubar which can be used in a frame
  • Menu("Type"); // defines a menu which can itself have hierarchically defined submemus
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.

HTML version of Basic Foils prepared 18 May 97

Foil 53 Abstract Windowing Toolkit (AWT):
Layouts

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index

HTML version of Basic Foils prepared 18 May 97

Foil 54 Layout of Components in a Panel

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 55 Description and Example of BorderLayout

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 56 Brief Description of Four Other LayoutManager's

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 57 FlowLayouts in detail

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 58 Hierarchical use of LayoutManagers

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 59 AWT - Grid Layout with Two Components

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 60 AWT - Adding Components to a Layout

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 1997. *
Full HTML Index

HTML version of Basic Foils prepared 18 May 97

Foil 61 AWT - Canvas Component

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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 18 May 97

Foil 62 AWT - Handling Actions from Components

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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.

HTML version of Basic Foils prepared 18 May 97

Foil 63 AWT - Panel Component with Buttons

From Java Tutorial - Spring 1997 Part 3:Graphics and the Abstract Windowing Toolkit Peking Tutorial, Web Certificate -- Spring-Summer 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.

© 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 Thu Jan 8 1998