View
222
Download
0
Category
Preview:
Citation preview
Computer Programming with JAVA
Chapter 7.Event-Driven Programming Using the AWTEvent-Driven Programming
GUIs and the AWTSimple Window InterfacesComponents, Containers, and Layout ManagersPanels and Text ComponentsAdding MenusInner Classes
Event-Driven Programming
A different approach to program design Programs react to events, e.g.
mouse click key press menu selection button selection message sent from printer etc.
GUI: graphical user interface windows, scroll bars, menus, radio buttons, etc. a special case of event-driven programming the only type of event we will be concerned with in this
chapter An event is an object
AWT
Abstract Window Toolkit Implements GUI A standard part of Java Not fancy, but adequate Makes extensive use of inheritance Based on events and event handlers Firing an event: when an object generates an
event Listener object
every object that can fire an event, such as a button, can have one or more listener objects
Listener objects have methods (called event handlers) that perform actions depending on the event
You the programmer write these event handlers
WARNING!
Programs that use the AWT can hang the computer
Save your work before runninga program using the AWT!
Chapter 6 Java: an Introduction to Computer Science & Programming - Walter Savitch 5
import java.awt.*;import java.awt.event.*;
public class FirstWindow extends Frame
Example: include the AWT library & extend Frame
The 1st two lines are needed when you use the AWT library
3rd line: starts the class definition
FirstWindow is derived from AWT Frame class
Frame is derived from the more basic class AWT Window class
Frame has a window, border, title bar, and close button
Frame will be modified by adding properties to meet the program requirements
The first few lines of FirstWindow(Display 7.1/page 329):
A word about displays: pixels Displays are organized as
a 2-dimensional grid of pixels
pixel: picture element the smallest
"addressable" unit of a screen
"Address" = coordinates (width, height)
The origin has coordinates (0,0) and is in upper left increasing width is to
right increasing height is down
(0, 0)
Increasing width (x direction)
Increasing height (y direction)
(75, 100)
Chapter 6 Java: an Introduction to Computer Science & Programming - Walter Savitch 7
public void paint(Graphics g) { g.drawString("Please, don't click that button!", 75, 100); }
Example: define paint method; Graphics class and drawString
FirstWindow inherits properties of Frame and adds paint method
paint is called by AWT, not by FirstWindow One argument, g, of type Graphics, is passed
think of it as a portion of the screen in which the object is to be painted Every Graphics object has a drawString method
75 and 100 are the coordinates of the start of the window• they depend on the programming environment• you may have to adjust the numbers• some things are done by trial and error: try it and see
Additional method paint (Display 7.1/page 329):
Chapter 6 Java: an Introduction to Computer Science & Programming - Walter Savitch 8
public class FirstWindow extends Frame{ public static final int WIDTH = 300; public static final int HEIGHT = 200; … public static void main(String[] args) { <program statements to define main> }
<program statements to define paint method>
}
Example:define system constants
Conventional style of declaring systemconstants (Display 7.1/page 329):
The window width and height are system constants that specify the window size in pixels
may adjust for different systems public allows other classes to
read the values static final prevents any
other class from changing the values
Using variables instead of "hard coded" numbers simplifies maintenance
just change these two lines and recompile to change the window size
avoids looking through the entire file for every occurrence of the numbers
Chapter 6 Java: an Introduction to Computer Science & Programming - Walter Savitch 9
public static void main(String[] args){ FirstWindow myWindow = new FirstWindow();1) myWindow.setSize(WIDTH, HEIGHT);
2) WindowDestroyer listener = new WindowDestroyer();3) myWindow.addWindowListener(listener);
4) myWindow.setVisible(true);}
Example: display window;define and register listeners
The main method(Display 7.1/page 329):
1) setSize: a Frame method to set the size of the window
2) listener: an object of the windowDestroyer class
an object that receives events from an object
should close window if "close window" button is clicked
must be defined (written)
3) Registering the listener associates the listener object
with an event-firing object the listener will listen for
events fired by the associated object
4) setVisible: a Frame method to make the window visible
Chapter 6 Java: an Introduction to Computer Science & Programming - Walter Savitch 10
import java.awt.*;import java.awt.event.*;…public class WindowDestroyer extends WindowAdapter{ public void windowClosing(WindowEvent e) { System.exit(0); }}
Example: windowAdapter abstract class and System.exit
windowDestroyer definition(Display 7.2/page 332):
windowAdapter Often the parent for windows
(descendents of Frame class) an abstract class: it has
methods but they are undefined, so you need to define whichever methods you will use
See Display 7.3/page 334 for windowAdapter methods
"close window" in the only event in this case
so windowClosing method must be defined
System.exit(0) ends the Java program
"0" is the conventional value used to indicate normal termination
Useful methods in Frame class
setTitle inserts a string in the title bar of the window
setBackground(Color.blue) specifies the background color of the window Display 7.6/page 343 lists other predefined color values
addWindowListener registers a listener for events
setSize and paint have already been described etc. - see Display 7.7/page 344
Two principle ways tocreate new classes from old ones
One method: Inheritance
Use extend to create a custom window based on an existing class
For example: … FirstWindow extends
Frame
Another: Container class Use a container class Use the add method to place
items in it Items placed in a container
class are called components Three kinds of objects to deal
with:1. The container class itself
(usually a window)2. The components to add to it3. The layout manager
AWT container class AWT container classes: Window, Panel, Frame
All three are descendents of the class Container Custom windows are built by adding components to a
container class, usually in the constructor Use the add method inherited from Container to place
items in the new (container) class Components: items added to a container
for windows: buttons, menus, text fields, etc. Component is also a class
The AWT class hierarchy with Container and Component classes is shown on the next slide (Display 7.9/page 350)
Hierarchy of AWT classesDisplay 7.9/page 350
Object
MenuComponentComponent
Container Button Menubar MenuItem
Window
Label
TextComponentPanel
Menu
Frame TextArea TextField
Class
Abstract Class
Key: If there is a line between two classes, then the lower class is a derived class of the higher class. Not all AWT components are shown.
AWT
Example: creating a window using a container class and components
ButtonDemo(Display 7.8/page 347)
The constructor is shown in box at right
Note the code to create and add buttons (shown in blue)
public ButtonDemo() { setSize(WIDTH, HEIGHT);
addWindowListener(new WindowDestroyer()); setTitle("Button Demonstration"); setBackground(Color.blue);
setLayout(new FlowLayout());
Button stopButton = new Button("Red"); stopButton.addActionListener(this); add(stopButton);
Button goButton = new Button("Green"); goButton.addActionListener(this); add(goButton); }
ButtonDemo constructor:
Example:drawString and repaint
The String instance variable theText is used as an argument in drawString so the text inside the window can be changed easily
actionPerformed method determines which event occurred (which button was clicked) and changes the value of theText accordingly
repaint()is called to update the window with the new value of theText
public void paint(Graphics g) { g.drawString(theText, 75, 100); }
public void actionPerformed(ActionEvent e) { <pseudocode to select which action to take> if(red) theText = "Stop!"; else if(green) theText = "Go!"; else theText = "Error in button interface.";
repaint(); //force color and text change }
private String theText = "Watch me!";}
Using a String instance variablein drawString:
Example: action listeners Different kinds of components require different kinds of listeners Buttons fire events of type ActionEvent which require action
listeners ActionListener is not a class, it is a property (or interface) of a
class To give the ActionListener property to a class:
1. Add implements ActionListener to the beginning of the class definition, e.g.:public class ButtonDemo extends Frame implements ActionListener{ <statements to define class> }
2. Define a method named actionPerformed Use addActionListener to add an action listener for a button,
e.g.: Button stopButton = new Button("Red");stopButton.addActionListener(this);
See definition of ButtonDemo, Display 7.8/page 347
actionPerformed method
Usually a selection (branching) statement that determines which action event fired and performs the appropriate action
getActionCommand reads the text value assigned to the whichever button was clicked
the text value was assigned when the Button object was created
public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Red")) { setBackground(Color.red); theText = "STOP"; } else if (e.getActionCommand().equals("Green")) { setBackground(Color.green); theText = "GO"; } else theText = "Error in button interface.";
repaint(); //force color and text change }
actionPerformed method for ButtonDemo:
Layout managers
Three basic layout managers provided with AWT:1. FlowLayout2. BorderLayout3. GridLayout
There are others but they are not covered in this text
FlowLayout
To create a FlowLayout object:setLayout(new FlowLayout());
Arranges components in the order they are added starting in upper left of window (or other object) and
proceeding to the right when the top line is full it goes to the next line, etc.
Example: ButtonDemo (Display 7.8/page 347) uses a flow layout
BorderLayout
To create a BorderLayout object:setLayout(new BorderLayout());
Components can be placed in any one of five regions "North" "South" "East" "West" "Center"
Example: BorderLayout
In the constructor for some container object:setLayout(new BorderLayout());add(new Button("Up"),"North");add(new Button("Down"),"South");add(new Button("Right"),"East");add(new Button("Left"),"West");add(new Button("Straight ahead"),"Center");
Up
Down
Left RightStraight ahead
The result:
GridLayout
Arranges components in a two-dimensional grid (rows and columns)
Each entry is the same size For a grid with two rows and three columns:setLayout(new GridLayout(2,3)); the first argument is the number of rows the second argument is the number of columns creates a layout like this:
Summary for creating simple window interface(1)
1. Derive a window object from Frame and add components.
2. You must register a window listener for the close-window button e.g., by adding the following to the GUI class definition
within a constructor: addWindowListener(new WindowDestroyer());
See Display 7.2/page 332 for a definition of WindowDestroyer.
3. Some components, e.g. buttons, generate action events, so the GUI (or some other class) must be made an action listener. Every component that generates an action event should
have an action listener registered with it. Use addActionListener to register an action listener.
Summary for creating simple window interface(2)
4. Use implements ActionListener at the beginning of the class definition to make your GUI (or other class) an action listener. You also need to add a definition of the method actionPerformed to the class.
5. There are other ways, but this one is simple and commonly used.
Programming tips
1. Don't reinvent the wheel: copy a similar program and modify it. Obviously there is a lot of detail to deal with, so start with a
program similar to what you need - the sample programs in each chapter are often good starting points for doing the Programming Exercises at the end of the chapter.
However, it is NOT ok to copy another student's work!
2. See Display 7.11/page 360 for an outline of the code to create a simple GUI class. You may want to create this file and use it as a template: copy it and modify the copy to create a new GUI.
WindowListener options
1. Make the window itself the button listener by implementing the ActionListener interface we did this when we placed buttons in a window
2. Make the window listener a separate class we did this for the window-closing button by defining WindowDestroyer
3. Make the window itself the window listener by implementing the WindowListener interface
More about interfaces Interfaces are just a collection of undefined methods A Java class can be derived from only one base class but
can implement more than one interface All methods in an interface must be defined
unused methods can be defined with empty bodies, e.g.public void windowDeiconified(WindowEvent e){}
ActionListener has only one method (ActionPerformed), but WindowListener has seven methods if you do not need the other methods, using ActionListener
instead of WindowListener avoids having to write the empty method definitions
The Panel class A container class to group objects Used to subdivide a Frame into different areas For example, if you want two buttons in the south area of a
border layout, put the two objects in a panel and place the panel in the south position
Typical program organization:Create new panel
set panel attributes, e.g. background color and panel layout
create and add objects such as buttons
Establish the overall layout and place the panel in the layout
Example code: Display 7.13/page 366
Example: Panel public PanelDemo() { setTitle("Panel Demonstration"); setSize(WIDTH, HEIGHT); setBackground(Color.blue); addWindowListener(new WindowDestroyer());
Panel buttonPanel = new Panel(); buttonPanel.setBackground(Color.white);
buttonPanel.setLayout(new FlowLayout());
Button stopButton = new Button("Red"); stopButton.setBackground(Color.red); stopButton.addActionListener(this); buttonPanel.add(stopButton);
Button goButton = new Button("Green"); goButton.setBackground(Color.green); goButton.addActionListener(this); buttonPanel.add(goButton);
setLayout(new BorderLayout()); add(buttonPanel, "South"); }
Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 30
create panel
place panel in GUI
PanelDemo constructorfrom Display 7.13/page 366
Resulting GUI for PanelDemo
Button Demonstration X
Watch me!
Red Green
TextArea and TextField classes
TextArea: defines an area to display text specifies how many lines and how many characters per line to
display TextField: also defines an area to display text
but only the number of characters in the line is specified the field has only one line
For both classes: The user can enter text in the field getText reads text entered by the user setText writes text to the field more text can be written to the field than the specified size, but
only an amount equal to the size will be displayed (the scroll bar must be used to see the remaining text)
initial text can be specified when the object is created with new
Example: TextArea
The constructor for TextAreaDemo (Display 7.14/page 369) creates a panel with a text area 10 lines by 40 characters
The panel color is set to blue and the background of the text area to white
The panel is placed in the center of the window
textPanel = new Panel();textPanel.setBackground(Color.blue);theText = new TextArea(10, 40);theText.setBackground(Color.white);textPanel.add(theText);add(textPanel, "Center");
Creating a text area (excerpt from Display 7.14/page 369):
Example: setText and getText
Using the same example, TextAreaDemo (Display 7.14/page 369):
Clear the text area:
theText.setText("");
Read the text entered by the user into String instance variable memo1:
memo1 = theText.getText();
Label class
Used to label text fields or other components
Typical program organization to attach a label to a text field:
Create new panel
set panel attributes, e.g. background color and panel layout
add text field and label
Place the panel in the layout
Example: Label
Excerpt from LabelDemo (Display 7.15/page 374)name = new TextField(20);namePanel.add(name, "South");Label nameLabel = new Label("Enter your name here:");namePanel.add(nameLabel, "Center");
Resulting GUI: Name Tester X
Test Clear
Enter your name here:
A very good name!A label
Inputting and outputting numbers in the AWT
Problem: the numbers read from or written to a text area are String type but we want numeric types all AWT input and output is String
Conversion methods are needed to convert from numeric types to String, and to convert String to numeric types
Inputting numbers: methods, methods, methods, ...
Numeric wrapper classes have a valueOf method that converts text numbers to the wrapper numeric type (Integer, Double, etc.) …
… but we often want the corresponding primitive type, so we also need to use the appropriate "Value" method (intValue, doubleValue, etc.) …
… and we want to ignore white space before and after the input, so the trim method is also used
Example:reading an integer from a text area
Combining all these results in a rather long statement, but it should make sense on careful analysis:
Input exampleRead an integer from text field inputOutputField:
int n = Integer.valueOf(inputOutputField.getText().trim()).intValue();
Outputting numbers
Not so many methods need to be strung together
Just use toString to convert a numeric value to String, and setText to write it to the text area.
Output exampleWrite an integer to text field inputOutputField:
int n = 31;inputOutputField.setText(Integer.toString(n));
Adding menus
In the AWT menus are not a component but are added in ways similar to adding components
Three AWT classes are used Menu Menu MenuItem
The basic approach is to use an add method to put MenuItems in a Menu and put Menus in a Menu.
Example:creating a menu
Menu memoMenu = new Menu("Memos");MenuItem m;m = new MenuItem("Save Memo 1");m.addActionListener(this);memoMenu.add(m);
m = new MenuItem("Save Memo 2");m.addActionListener(this);memoMenu.add(m);
m = new MenuItem("Get Memo 1");m.addActionListener(this);memoMenu.add(m);
m = new MenuItem("Get Memo 2");m.addActionListener(this);memoMenu.add(m);
m = new MenuItem("Clear");m.addActionListener(this);memoMenu.add(m);
m = new MenuItem("Exit");m.addActionListener(this);memoMenu.add(m);
MenuBar mBar = new MenuBar();mBar.add(memoMenu);setMenuBar(mBar);
Chapter 7 Java: an Introduction to Computer Science & Programming - Walter Savitch 42
Excerpt from MenuDemo constructor(Display 7.18/page 386)
The resulting GUI before and afterclicking Memos is shown on page 388
Note: the method to add a menu bar is setMenuBar, not add
Inner classes
An inner class is a class that is defined inside another class A full description is beyond the scope of this text However, one situation has already been described:
using the AWT to create GUIs Another simple situation is common and is also described:
helping classes Moving the definition of a helping class inside the class
definition has two advantages: it allows the helping class to access all instance variables,
including private ones it improves the level of information hiding
For these reasons inner classes are often used as listeners to handle events fired within the outer class
Summary ...
GUIs are written using event-driven programming In event-driven programming, a user action, like a mouse
click, generates an event and the that event is automatically passed to an event-handling program to perform the appropriate action.
Two main ways to build a GUI with the AWT:1. Use inheritance to create a derived class from a preexisting one2. Add components to a container
A window is defined as a derived class of Frame A button is an object of the class button The add method is used to add components to a container Components in a container are arranged by a layout
manager object
… summary, continued A panel is a container to organize objects inside a larger
container. Text fields and text areas are used by GUIs for input and
output of text, including numbers in text format methods exist to convert numeric types to and from text
MenuBars are created by adding Menus and MenuItems in a manner similar to putting components in containers, but they are not members of the classes Container or Components
Both buttons and menu items fire action events and so should have an ActionListener registered with them to respond to the event
Recommended