Week 9: Java GUI Part II
Overview of Events Handling
- Different then JDK 1.0
- JDK 1.1 event model
- JDK use kind of a client-server model (one sends request,
the other listen)
- AWT objects send out request (as a client) when something
happens
- Button clicked (ActionEvent)
- Choice item changed (ItemEvent)
- Menu item selected (ActionEvent)
- Key pressed (keyEvent)
- Window closed (WindowEvent)
- java.awt.event package
Some more Syntax - The Inner classes
- classes that are defined within a class
- When you compile using javac, the one with $ in the name
field is usually the inner class
- public, private, or protected can be used
- good for small classes (for example, some listners in the
UI Model)
- good as "helper" class only used with another
class
- sometimes perfect for listener implementations
- anonymous inner classes are coded inline.
- must only access local final variables, or access global
variables
- sometimes we must use temp variable to make it compile
(see example below)
Frame f = new Frame("My frame");
Button quit = new Button("Quit");
// Create a temp variable which must be final
final Frame f2 = f;
// Create a anonymous class which act as a listner for the button
quit.addActionListener (new ActionListener ()
{
public static void actionPerformed (ActionEvent event)
{
f2.dispose();
}
});
Example:
/*
* A frame that will close when user select to close the window
*/
import java.awt.*;
import java.awt.event.*;
public class CloseableFrame extends Frame
{
public CloseableFrame()
{
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{ System.exit(0); }
} );
setSize(300, 200);
setTitle(getClass().getName());
}
}
Listeners
- listeners are like servers in a client-server model
- listeners are mapped with UI componet(s) (Button, List,
etc)
- listeners are "notified" when events are fired
(when UI component sends out request)
- listeners are classes themself
- being "notified" means one of the listeners
methods is called
- listeners are defined as interfaces, e.g.
- ActionListener
- ItemListener
- KeyListener
- WindowListener
- listener interfaces define 1 or more notification method
- to process events, your program:
- implements listener interfaces
- adds listeners to components
- you can implement many listener interfaces:
- all in one class (sometimes hard to debug)
- all in separate classes (lots of very small
classes to deal with)
- using "inner classes" (the syntax
drives you nuts)
- Whether you use separate class or inner class or the same
class depends on the project
- many listeners can listen to the same component
Examples:
// Here is a class that implements the ActionListener interface.
// There is only one noticication method.
class MyActionListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
System.out.println("The button was pressed.");
}
}
// In another file with some other class, we
// create a button.
Button b = new Button("Hit me");
// Add our custom action listener to the button.
MyActionListener customActionListener = new MyActionListener ();
b.addActionListener (customActionListener);
//Now, when ever the button is pressed,
// MyActionListener.actionPerformed() is called
ActionEvent and ActionListener
- ActionEvent fired whenever a button is pressed or a menu
item is selected
- when an ActionEvent is fired, ActionListener
actionPerformed() is called
- use addActionListener() to add listeners to buttons or
menu items
- If a single ActionListener needs to handle several
buttons and/or menu items, it can get the source using
ActionEvent.getSource()
- true for all events and listeners
ItemEvent and ItemListener
- ItemEvent fired whenever a item is selected in a Choice
- when an ItemEvent is fired,
ItemListener.itemStateChanged() is called
- use ItemEvent.getItem() to get the item that was selected
- use addItemListener() to add listeners to choices
Example:
// Here is a class that implements the ItemListener Interface
class MyItemListener implements ItemListener
{
public void itemStateChanged (ItemEvent event)
{
System.out.println("Item " + event.getItem() + "was selected,");
}
}
// Here is a code snippet that creates a choice and
// processes item selections (assume this is inside a main, etc.)
// Create a choice.
Choice ch = new Choices();
ch.add("Visa");
ch.add("Mastercard");
ch.add("Discover");
ch.add("American Express");
// Add our custom item listener to the choice.
MyItemListen customItemListener = new MyItemListener();
ch.addItemListener (customItemListener);
// Now, when ever an item is selected,
// MyItemListener.itemStateChanged() is called.
KeyEvent and KeyListener
- KeyEvent fired whenever a key is pressed
- when a KeyEvent is fired, either of the following is
called:
- KeyListener.keyPressed() is called when a key is
pressed
- KeyListener.keyReleased() is called when a key is
pressed
- KeyListener.keyTyped() is called when a key is
pressed and released
- use addKeyListener() to add listeners to text components
- use KeyEvent.getKeyCode() and KeyEvent.getKeyChar() to
determine what key was pressed
- see p. 317 for possible key codes
- if your listener does not need to process all three kinds
of KeyEvents, then extend KeyAdapter
Example:
// Here is a class that implements the KeyListener interface
// (by extending the KeyAdapter class).
class MyKeyListener extends KeyAdapter
{
public void keyPressed (KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.VK_ENTER)
System.out.println("Enter was pressed");
}
}
// Here is a code snippet that creates a text field and
// processes the enter key (assume this is inside a main, etc.)
// Create a text field.
TextField tf = new TextField(30);
tf.setText("");
// Add our custom key listener to the text field.
MyKeyListener customKeyListener = new MyKeyListener();
tf.addKeyListener (customKeyListener);
// Now, when ever the enter key is pressed in the text field,
// MyKeyListener.keyPressed() is called
WindowEvent and WindowListener
- WindowEvent fired whenever something happens to a window
- when a WindowEvent is fired, either of the following is
called:
- WindowListener.windowClosing()
- WindowListener.windowClosed()
- WindowListener.windowOpened()
- WindowListener.windowIconified()
- WidnowListener.windowActivated()
- WindowListener.windowDeactivated()
- use addWindowListener() to add listeners to windows
- if your listener does not need to process all seven kinds
of WindowEvents, then extend WindowAdapter
Example
// Here is a class that implements the WindowListener interface
// (by extending the WindowAdapter class).
class MyWindowListener extends WindowAdapter
{
public void windowIconified (WindowEvent event)
{
System.out.println("Window was iconified.");
}
public void windowDeiconified (WindowEvent event)
{
System.out.println("Window was deiconified.");
}
}
// Here is a code snippet that creates a frame and reports
// when it is iconified and deiconified
// (assume this is inside a main, etc)
// Create a frame.
Frame f = new Frame("This is only a test");
// Add our custom window listener to the frame
MyWindowListener customWindowListener = new MyWindowListener ();
f.addWindowListener (customWindowListener);
// Show the frame
f.show();
// Now, when ever the window is iconified or deiconified,
// the custom window listener methods are called.
What else ?
- Many more types of events and listeners
- Events and listeners can be used for non-visual
components, too
- You can create your own events and listeners
- Java Beans - standard component model
Lab
Create a GUI applicaton Week9 that
has the following look and feel:

Then:
- Create a class called ItemColorChanger
which is an implementation of ItemListener that changes
the color of a component based on what item was selected.
- Add an ItemColorChanger as an item listener to the choice
object, so that it changes the color of the text area.
- Create a class called ButtonTextChanger
which is an implementation of ActionListener that sets
the text of a text component to the button label whenever
a button is clicked.
- Add a ButtonTextChanger as an action listener to the
buttons, so that they change the text of the text area
- Add an ActionListener to the Exit menu so that it closes
the window when selected. Use an anonymous inner class
- Add a WindowListener to the frame that prints a goodbye
message and exits when the window is closing. Use an
anonymous inner class that extends WindowAdapter.