You are on page 1of 10

Chapter 12: Event Handling (3 hrs) Chapter Objective: Define what event are.

. Define what event handling are. Write code to handle events that occur in a GUI Describe the five (5) ways on how to implement event handling technique. Event handling is of fundamental importance to programs with a graphical user interface. To implement user interfaces, you must master the way in which Java handles events. This chapter explains how the Java AWT event model works. You will see how to capture events from user interface components and input devices. We also show you how to work with actions, a more structured approach for processing action events. Basics of Event Handling Any operating environment that supports GUIs constantly monitors events such as keystrokes or mouse clicks. The operating environment reports these events to the programs that are running. Each program then decides what, if anything, to do in response to these events. In languages like Visual Basic, the correspondence between events and code is obvious. One writes code for each specific event of interest and places the code in what is usually called an event procedure. For example, a Visual Basic button named HelpButton would have a HelpButton_Click event procedure associated with it. The code in this procedure executes whenever that button is clicked. Each Visual Basic GUI component responds to a fixed set of events, and it is impossible to change the events to which a Visual Basic component responds. On the other hand, if you use a language like raw C to do event-driven programming, you need to write the code that constantly checks the event queue for what the operating environment is reporting. (You usually do this by encasing your code in a loop with a massive switch statement!) This technique is obviously rather ugly, and, in any case, it is much more difficult to code. The advantage is that the events you can respond to are not as limited as in languages, like Visual Basic, that go to great lengths to hide the event queue from the programmer. The Java programming environment takes an approach somewhat between the Visual Basic approach and the raw C approach in terms of power and, therefore, in resulting complexity. Within the limits of the events that the AWT knows about, you completely control how events are transmitted from the event sources (such as buttons or scrollbars) to event listeners. You can designate any object to be an event listenerin practice, you pick an object that can conveniently carry out the desired response to the event. This event delegation model gives you much more flexibility than is possible with Visual Basic, in which the listener is predetermined.

What is an Event? Events are Objects that describes what happens. Events may be a button click, a mouse passover, a keyboard short cut or any interaction to a GUI component. What is an Event Source? Event sources are GUI components in which the user invoked an interaction. Event sources have methods that allow you to register event listeners with them. When an event happens to the source, the source sends a notification of that event to all the listener objects that were registered for that event. As one would expect in an object-oriented language like Java, the information about the event is encapsulated in an event object. In Java, all event objects ultimately derive from the class
Page 1 of 10 Prepared by: Lawrence G. Decamora III, scjp

java.util.EventObject. Of course, there are subclasses for each event type, such as ActionEvent and WindowEvent. Different event sources can produce different kinds of events. For example, a button can send ActionEvent objects, whereas a window can send WindowEvent objects. To sum up, heres an overview of how event handling in the AWT works:

A listener object is an instance of a class that implements a special interface called (naturally enough) a listener interface. An event source is an object that can register listener objects and send them event objects. The event source sends out event objects to all registered listeners when that event occurs. The listener objects will then use the information in the event object to determine their reaction to the event. This is the relationship between event handling classes and interfaces.

What is an Event Handler? An Event Handler is a method that is invoked every time that an event is called. This is where you code the behavior you want to do every time an event occurs. Five (5) ways to do Event Handling. 1. The Event Delegation Model. It allows you to delegate the event handler to a different class, thus producing a loosely coupled GUI and Event Handler package. Each class will be from a separate Java source file. You can create as many event handlers as you want, the important thing after creating them is to register them for them to be used. This is how you register an event handler: private Button b; . . . b = new Button("Press Me!"); . . . b.addActionListener(new ButtonHandler()); b.addActionListener(new MyOwnEventHandler()); Create the button first, then use the addActionListener method to add the instance of your event handlers.

Page 2 of 10

Prepared by: Lawrence G. Decamora III, scjp

// TestButton.java import java.awt.*; public class TestButton { private Frame f; private Button b; public TestButton() { f = new Frame("Test"); b = new Button("Press Me!"); b.setActionCommand("ButtonPressed"); } public void launchFrame() { b.addActionListener(new ButtonHandler()); b.addActionListener(new MyOwnEventHandler()); f.add(b,BorderLayout.CENTER); f.pack(); f.setVisible(true); } public static void main(String args[]) { TestButton guiApp = new TestButton(); guiApp.launchFrame(); } } // ButtonHandler.java import java.awt.event.*; public class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Action occurred"); System.out.println("Button's command is: " + e.getActionCommand()); } } // MyOwnEventHandler.java import java.awt.event.*; public class MyOwnEventHandler implements ActionListener { public void actionPerformed(ActionEvent ae) { System.out.println("The other event handler.."); } } The reason why it is called delegation model is because we created a different class in where the event handling technique will be delegated. An event may be sent to many event handlers as long as they are registered to the component Most components can trigger more than one type of event depending on the number of event handler registered to them.
Page 3 of 10 Prepared by: Lawrence G. Decamora III, scjp

2. The Use of Interfaces (Listeners) All Event Listeners are Interfaces, which means once you implement them you are required to override all the event handlers (methods) declared in those listeners (interfaces) even the once that you don't need. As of Java SE 5.0, here are the list of listeners (interfaces) and their corresponding event handlers (methods) that needs to be overridden. Category Action Item Mouse Interface Name ActionListener ItemListener MouseListener Methods actionPerformed(ActionEvent) itemStateChange(ItemEvent) mousePressed(MouseEvent) mouseReleased(MouseEvent) mouseEntered(MouseEvent) mouseExited(MouseEvent) mouseClicked(MouseEvent) Mouse motion Key MouseMotionListener KeyListener mouseDragged(MouseEvent) mouseMoved(MouseEvent) keyPressed(KeyEvent) keyReleased(KeyEvent) keyTyped(KeyEvent) Focus Adjustment Component FocusListener AdjustmentListener ComponentListener focusGained(FocusEvent) focusLost(FocusEvent) adjustmentValueChanged(AdjustmentEvent) componentMoved(ComponentEvent) componentHidden(ComponentEvent) componentResized(ComponentEvent) componentShown(ComponentEvent) Window WindowListener windowClosing(WindowEvent) windowOpened(WindowEvent) windowIconified(WindowEvent) windowDeiconified(WindowEvent) windowClosed(WindowEvent)
Page 4 of 10 Prepared by: Lawrence G. Decamora III, scjp

windowActivated(WindowEvent) windowDeactivated(WindowEvent) Container Text ContainerListener TextListener componentAdded(ContainerEvent) componentRemoved(ContainerEvent) textValueChanged(TextEvent)

Take this sample code for example, you've implemented MouseMotionListener and MouseListener, which means, based on the given table above, you must override seven (7) event handlers (methods), five (5) from MouseListener and two (2) from MouseMotionListener // TwoListener.java 1 import java.awt.*; 2 import java.awt.event.*; 3 4 public class TwoListener 5 implements MouseMotionListener, 6 MouseListener { 7 private Frame f; 8 private TextField tf; 9 10 public TwoListener() { 11 f = new Frame("Two listeners example"); 12 tf = new TextField(30); 13 } 14 15 public void launchFrame() { 16 Label label = new Label("Click and drag the mouse"); 17 // Add components to the frame 18 f.add(label, BorderLayout.NORTH); 19 f.add(tf, BorderLayout.SOUTH); 20 // Add this object as a listener 21 f.addMouseMotionListener(this); 22 f.addMouseListener(this); 23 // Size the frame and make it visible 24 f.setSize(300, 200); 25 f.setVisible(true); 26 } 27 28 // These are MouseMotionListener events 29 public void mouseDragged(MouseEvent e) { 30 String s = "Mouse dragging: X = " + e.getX() 31 + " Y = " + e.getY(); 32 tf.setText(s); 33 } 34 35 public void mouseEntered(MouseEvent e) { 36 String s = "The mouse entered"; 37 tf.setText(s); 38 } 39 40 public void mouseExited(MouseEvent e) { 41 String s = "The mouse has left the building"; 42 tf.setText(s);
Page 5 of 10 Prepared by: Lawrence G. Decamora III, scjp

43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

} // Unused MouseMotionListener method. // All methods of a listener must be present in the // class even if they are not used. public void mouseMoved(MouseEvent e) { } // Unused MouseListener methods. public void mousePressed(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public static void main(String args[]) { TwoListener two = new TwoListener(); two.launchFrame(); } }

However, in some cases, you don't need to use all seven, in the sample code you only used three(3). Even so, you are still required to overide all seven (7), the other four (4) unused methods must still be overridden, having empty implementations. 45 46 47 48 49 50 51 52 53 // Unused MouseMotionListener method. // All methods of a listener must be present in the // class even if they are not used. public void mouseMoved(MouseEvent e) { } // Unused MouseListener methods. public void mousePressed(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseReleased(MouseEvent e) { }

3. The Use of Abstract Classes (Adapter Classes) There are instances that it is better to use Adapter Classes rather Listeners. For example, if you will implement WindowListener you are required to override seven (7) methods even if you only need one. In this case, it is better to extend WindowAdapter and override the single method that you need. In our SimpleCalculator class, you will see this code snipplet: private class MyCloseButtonHandler extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); } } This one is better because in this application, I only need the windowClosing(WindowEvent) method and not all seven (7) methods.

Page 6 of 10

Prepared by: Lawrence G. Decamora III, scjp

4. Inner Classes The concept of Inner Classes is used to make tightly coupled components. As for the GUI Apps, it is used to group the GUI code and Event Handler Code. In our SimpleCalculator App, you will see this sample code snipplet which demonstrates the use of inner classes as event handlers: 1 package myapp; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 6 public class SimpleCalculator implements ActionListener 7 { 8 // containers 9 private Frame f; 10 private Panel p1, p2, p3, p4; 11 12 // components 13 private Label l1, l2, l3; 14 private TextField tf1, tf2, tf3; 15 private Button bAdd, bSub, bMul, bDiv, bQuit; 16 . . . . . . . . . 116 private class MyCloseButtonHandler extends WindowAdapter 117 { 118 public void windowClosing(WindowEvent we) 119 { 120 System.exit(0); 121 } 122 } . . . . . . . . . 129 } 5. Anonymous Classes Anonymous Classes are used to create on the fly objects or objects that are anonymous. These are event objects that does not have any handler or object references. These event objects are created so that you can access and execute their corresponding event handlers after which they are automatically destroyed which leaves your memory at an optimized state. Usually, Anonymous classes are used for mobile devices or even desktop applications that you would like to execute at an efficient runtime. Here's an example that uses Anonymous Class as its event handling technique. 1 2 3 4 5 6 7
Page 7 of 10

import java.awt.*; import java.awt.event.*; public class TestAnonymous { private Frame f; private TextField tf;

Prepared by: Lawrence G. Decamora III, scjp

8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

public TestAnonymous() { f = new Frame("Anonymous classes example"); tf = new TextField(30); } public static void main(String args[]) { TestAnonymous obj = new TestAnonymous(); obj.launchFrame(); } public void launchFrame() { Label label = new Label("Click and drag the mouse"); // Add components to the frame f.add(label, BorderLayout.NORTH); f.add(tf, BorderLayout.SOUTH); // Add a listener that uses an anonymous class f.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { String s = "Mouse dragging: X = "+ e.getX() + " Y = " + e.getY(); tf.setText(s); } }); // <- note the closing parenthesis f.addMouseListener(new MouseClickHandler()); // Not shown // Size the frame and make it visible f.setSize(300, 200); f.setVisible(true); } }

To complete our SimpleCalculatorSwing Application, here's the sample code. import java.awt.*; import javax.swing.*; import java.awt.event.*; public class SimpleCalculatorSwing implements ActionListener { // containers private JFrame f; private JPanel p1, p2, p3, p4; // containers private JLabel l1, l2, l3; private JTextField tf1, tf2, tf3; private JButton bAdd, bSub, bMul, bDiv, bQuit; public SimpleCalculatorSwing() { // containers f = new JFrame("My First GUI App"); p1 = new JPanel(); p2 = new JPanel(); p3 = new JPanel();
Page 8 of 10 Prepared by: Lawrence G. Decamora III, scjp

p4 = new JPanel(); // l1 l2 l3 components = new JLabel("First: "); = new JLabel("Second: "); = new JLabel("Result: ");

tf1 = new JTextField("0.0", 15); tf2 = new JTextField("0.0", 15); tf3 = new JTextField("0.0", 15); bAdd = new JButton("+"); bSub = new JButton("-"); bMul = new JButton("*"); bDiv = new JButton("/"); bQuit = new JButton("Q"); } public void launchFrame() { // use the default layout manager of the Panel. p1.add(l1); p1.add(tf1); p2.add(l2); p2.add(tf2); p3.add(l3); p3.add(tf3); p4.add(bAdd); p4.add(bSub); p4.add(bMul); p4.add(bDiv); p4.add(bQuit); // change the layout manager of the frame to GridLayout(4, 1); f.setLayout(new GridLayout(4,1)); f.add(p1); f.add(p2); f.add(p3); f.add(p4); f.pack(); f.setVisible(true); // register the event handlers bAdd.addActionListener(this); bSub.addActionListener(this); bMul.addActionListener(this); bDiv.addActionListener(this); bQuit.addActionListener(this); f.addWindowListener(new CloseHandler()); } // override the actionPerformed method public void actionPerformed(ActionEvent ae)
Page 9 of 10 Prepared by: Lawrence G. Decamora III, scjp

Object source = ae.getSource(); double num1, num2, result = 0.0; if (tf1.getText() != null && tf2.getText() != null) { num1 = Double.parseDouble(tf1.getText()); num2 = Double.parseDouble(tf2.getText()); if (source == bAdd) { result = num1 + num2; } else if (source == bSub) { result = num1 - num2; } else if (source == bMul) { result = num1 * num2; } else if (source == bDiv) { result = num1 / num2; } else if (source == bQuit) { System.exit(0); } else {} // tf3.setText(new Double(result).toString()); tf3.setText("" + result);

} } private class CloseHandler extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); } } public static void main(String args[]) { SimpleCalculatorSwing sc = new SimpleCalculatorSwing(); sc.launchFrame(); }

Notice that in this application, I've included more than one way of event handling technique.

Page 10 of 10

Prepared by: Lawrence G. Decamora III, scjp

You might also like