Objectives |
|
All the programs so far execute in a procedural order. This chapter introduces event-driven programming. In event-driven programming , code is executed when an event occurs (e.g., a button click or a mouse movement).
Before delving into event-driven programming, it is helpful to get a taste using a simple example. The example displays a button in the frame. A message is displayed on the console when a button is clicked, as shown in Figure 14.1.
The program is given in Listing 14.1. When a button is clicked, an event is fired from the button. The button is the source of the event. A listener object is created in line 11 and is registered with the button in line 12. When an action event occurs on the button, the button notifies the listener by invoking the listener's actionPerformed method (line 27).
1 import javax.swing.*; 2 import java.awt.event.*; 3 import java.awt.*; 4 5 public class SimpleEventDemo extends JFrame { 6 public SimpleEventDemo() { 7 JButton jbtOK = new JButton( "OK" ); 8 setLayout( new FlowLayout()); 9 add(jbtOK); 10 11 ActionListener listener = new OKListener(); 12 jbtOK.addActionListener(listener); 13 } 14 15 /** Main method */ 16 public static void main(String[] args) { 17 JFrame frame = new SimpleEventDemo(); 18 frame.setTitle( "SimpleEventDemo" ); 19 frame.setLocationRelativeTo( null ); // Center the frame 20 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 21 frame.setSize( 220 , 80 ); 22 frame.setVisible( true ); 23 } 24 } 25 26 class OKListener implements ActionListener { 27 public void actionPerformed(ActionEvent e) { 28 System.out.println( "It is OK" ); 29 } 30 } |
Now that you have had a taste of event-driven programming, you probably have many questions, such as why a listener class is declared to implement the ActionListener interface. This chapter will give you all the answers.