10.7. (Optional GUI) Handling GUI Events |
When you run the program in Listing 9.12, it displays two buttons . If you click a button, there is no response. To respond, you need to write the code to process the clicking button action. The button is a source object where the action originates. You need to create an object capable of handling the action event on a button. This object is called a listener . Not all objects can be listeners for an action event. To be a listener, two requirements must be met:
The object must be an instance of the ActionListener interface. The ActionListener interface contains the actionPerformed method for processing the event.
The ActionListener object listener must be registered with the source using the method source.addActionListener(listener) .
Listing 10.6 gives the code that processes the ActionEvent on the two buttons. When you click the OK button, the message "OK button clicked" is displayed. When you click the Cancel button, the message "Cancel button clicked" is displayed, as shown in Figure 10.10.
1 import javax.swing.*; 2 import java.awt.*; 3 import java.awt.event.*; 4 5 public class HandleEvent extends JFrame { 6 public HandleEvent() { 7 // Set FlowLayout for the frame 8 FlowLayout layout = new FlowLayout(); 9 setLayout(layout); 10 11 // Add two buttons to frame 12 JButton jbtOK = new JButton( "OK" ); 13 JButton jbtCancel = new JButton( "Cancel" ); 14 add(jbtOK); 15 add(jbtCancel); 16 17 // Register listeners 18 OKListenerClass listener1 = new OKListenerClass(); 19 CancelListenerClass listener2 = new CancelListenerClass(); 20 jbtOK.addActionListener(listener1); 21 jbtCancel.addActionListener(listener2); 22 } 23 24 public static void main(String[] args) { 25 JFrame frame = new HandleEvent(); 26 frame.setTitle( "Handle Event" ); 27 frame.setSize( 200 , 150 ); 28 frame.setLocation( 200 , 100 ); 29 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 30 frame.setVisible( true ); 31 } 32 } 33 34 class OKListenerClass implements ActionListener { 35 public void actionPerformed(ActionEvent e) { 36 System.out.println( "OK button clicked" ); 37 } 38 } 39 40 class CancelListenerClass implements ActionListener { 41 public void actionPerformed(ActionEvent e) { 42 System.out.println( "Cancel button clicked" ); 43 } 44 } |
Two listener classes are declared in lines 34 “44. Each listener class implements ActionListener to process ActionEvent . The object listener1 is an instance of OKListenerClass (line 18), which is registered with the button jbtOK in line 20. When the OK button is clicked, the actionPerformed(ActionEvent) method (line 36) in OKListenerClass is invoked to process the event. The object listener2 is an instance of CancelListenerClass (line 19), which is registered with the button jbtCancel in line 21. When the OK button is clicked, the actionPerformed(ActionEvent) method (line 42) in CancelListenerClass is invoked to process the event.