Download presentation
Presentation is loading. Please wait.
1
Unit 111 Event-Driven Programming Listener or Event handler Example: Handling Button Events Example: Handling Mouse Events Example: Handling Keyboard Events Adapter Classes Example: Handling Window Events Example: Handling Text Field Events Exercises Learning Outcomes oExtend the example programs to write more interesting GUI oUse nested classes and adapter classes to write medium-sized applications.
2
Unit 112 Listener or Event handler Listener: An object interested in being notified when an event occurs in a given component. A Listener object registers with a component to be notified of events generated by it. Listener must implement the event listener interface associated with events for which it registered. Programming a Listener for an event means: Implementing the interface associated with the event type. Registering it as an event listener on the appropriate event source.
3
Unit 113 Events Revisited Some events are generated only by certain components. But we can set up a listener on any component for any of the following events: –Component event - changing a component's size, position, or visibility. –Focus event - gaining or losing the keyboard focus. –Key event - pressing, releasing, or clicking keyboard keys. –Mouse event - clicking the mouse button and moving the mouse onto and off of a component. –Mouse motion event - moving or dragging a mouse over a component.
4
Unit 114 Events and Event listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while typing in a text field, or chooses a menu item ActionListener User closes a frame (main window)WindowListener User presses a mouse button while the cursor is over a component MouseListener User moves the mouse over a componentMouseMotionListener Component becomes visibleComponentListener Component gets the keyboard focusFocusListener Any property in a component changes such as the text on a label PropertyChangeListener When an item such as a check box is changedItemListener
5
Unit 115 Each event is represented by an object –Contains information about the event Event source –Generates event –Usually a GUI component Event listener –Responds to the event –Can be any Java class that implements correct interface User clicks a button -- ActionListener User closes a frame -- WindowListener User presses a mouse button -- MouseListener User moves the mouse -- MouseMotionListener Component becomes visible -- ComponentListener A single source can have multiple listeners A single listener can listen to multiple sources Event Handling
6
Unit 116 –Every event handler requires three pieces of code: Code that specifies that the class implements a listener interface. public class MyClass implements ActionListener { Code that registers an instance of the event handler class as a listener upon one or more components. someComponent.addActionListener(instance Of MyClass); Code that implements the methods in the listener interface. For example: public void actionPerformed(ActionEvent e) {...//code that responds to the event... } Event Handling
7
Unit 117 Example 1: Adding Components to Containers 1 import java.awt.*; 2 import javax.swing.*; 3 public class AddingComponents extends JFrame{ 4 JButton button = new JButton("Press Me"); 5 JLabel label = new JLabel( "Running Total:"); 6 JTextField textField = new JTextField(10); 7 Container cp = getContentPane(); 8 public AddingComponents() { 9 super("A Container With Components"); 10 setSize(300,100); 11 cp.setLayout(new FlowLayout()); 12 cp.add(label); 13 cp.add(textField); 14 cp.add (button); 15 setVisible(true); } 16 public static void main(String args []) { 17 new AddingComponents(); 18 } }
8
Unit 118 Handling Button Events This example builds on Example 1 of the preceding section. Notice that when the button is pushed in that example, nothing happens. We will add some code to respond to the button pushes. When the mouse is pushed it generates and ActionEvent. Thus, we will be implementing the corresponding ActionListener interface. ActionListener consists of the method:
9
Unit 119 Example 2: Button Events 1 import java.awt.*; 2 import java.awt.event.*; 3 class ButtonEventTest extends AddingComponents 4 implements ActionListener{ 5 private int sum; 6 public ButtonEventTest() { 7 button.addActionListener(this); 8 } 9 public void actionPerformed(ActionEvent ae) { 10 sum += 1; 11 textField.setText(sum+""); 12 Toolkit.getDefaultToolkit().beep(); 13 } 14 public static void main(String args []) { 15 new ButtonEventTest(); 16 } 17 }
10
Unit 1110 Handling Mouse Events This example illustrates how mouse events can be responded to. It also shows how a single listener can register with many sources. The event listener in this case will implement the MouseListener interface. MouseListener consists of five methods: The program is given in the following page.
11
Unit 1111 Example 3: Mouse Events 1 import java.awt.*; import java.awt.event.*; 2 public class MouseEventTest extends ButtonEventTest{ 3 public MouseEventTest(){ 4 class LightUpListener extends MouseAdapter { 5 public void mouseEntered(MouseEvent e) { 6 Component c = (Component)e.getSource(); 7 c.setBackground(Color.green); 8 } 9 public void mouseExited(MouseEvent e) { 10 Component c = (Component)e.getSource(); 11 c.setBackground(Color.red); 12 } 13 } 14 MouseListener listener = new LightUpListener(); 15 button.addMouseListener(listener); 16 textField.addMouseListener(listener); 17 cp.addMouseListener(listener); 18 } 19 public static void main(String[] args) { 20 new MouseEventTest(); 21 } } a single listener can register with many sources
12
Unit 1112 Handling Keyboard Events This example illustrates how keyboard events can be responded to. To receive KeyEvent, a component must have keyboard focus. We will be implementing the KeyListener interface. KeyListener consists of three methods: Notice that when you press a key, at least two events are generated.
13
Unit 1113 Example 4: Keyboard Events 1 import java.awt.*; import java.awt.event.*; 2 import javax.swing.JApplet; 3 public class KeyEventTest extends JApplet implements KeyListener{ 4 private String msg = ""; 5 private int startX = 10, startY = 10; 6 public void keyPressed(KeyEvent ke){ 7 showStatus ("Key Down"); 8 } 9 public void keyReleased(KeyEvent ke) {showStatus("Key Up"); } 10 public void keyTyped(KeyEvent ke){ 11 msg += ke.getKeyChar(); 12 repaint(); 13 } 14 public void init(){ 15 requestFocus(); 16 addKeyListener(this); 17 } 18 public void paint(Graphics g){ 19 g.drawString(msg,startX,startY); 20 } 21 }
14
Unit 1114 Introduction to Adapter Classes From previous examples, listener interfaces can have several methods. A particular listener may not be interested in all the methods. Nevertheless, the listener must implement all methods in the interface. Java provides adapter classes for implementing handlers selectively. Most listener interfaces with two or more methods have matching adapter classes. Java provides a collection of abstract event adapter classes. These adapter classes implement listener interfaces with empty, do-nothing methods. To implement a listener class, we extend an adapter class and override only methods needed.
15
Unit 1115 Handling Window Events This example shows how window events can be handled. The listener should implement the WindowListener interface. WindowListener consists of seven methods: We will extend the corresponding WindowAdapter in this example.
16
Unit 1116 Example 5: Window Events 1 import javax.swing.*;import java.awt.event.*; 2 class WindowEventTest extends JFrame{ 3 private String msg = "Are you sure you want to Quit Window?"; 4 public WindowEventTest() { 5 super("Window Event Test"); setSize(300,300); 6 addWindowListener(new WindowAdapter(){ 7 public void windowClosing(WindowEvent we) { 8 WindowEventTest obj = WindowEventTest.this; 9 int result = JOptionPane.showConfirmDialog(obj, msg); 10 if (result == JOptionPane.YES_OPTION) 11 System.exit(0); 12 else { 13 int keepOpen = WindowConstants.DO_NOTHING_ON_CLOSE; 14 setDefaultCloseOperation(keepOpen); 15 } 16 }}); 17 } 18 public static void main(String args [] ) { 19 WindowEventTest wt = new WindowEventTest(); 20 wt.setVisible(true); 21 } }
17
Unit 1117 Handling Text Field Events This example shows how texfield events are generated and handled. It also illustrates the use of multiple handlers. Two text fields are shown handling an ActionEvent in different ways. The program implements Celcius to Fahrenheit temperature conversions. You enter a temperature value in one text field and get the equivalent in the other. The complete program follows in the next page.
18
Unit 1118 Example 6: Text Field Events 1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 class TextFieldEventTest extends JFrame{ 5 JTextField celcius = new JTextField(10); 6 JTextField fahrenheit = new JTextField(10); 7 Container c = getContentPane(); 8 TextFieldEventTest(){ 9 c.setLayout(new FlowLayout()); 10 c.add(new JLabel("Celcius")); 11 c.add(celcius); 12celcius.addActionListener(new ActionListener() { 13 public void actionPerformed(ActionEvent ae){ 14 String cString = celcius.getText(); 15 double cValue = Double.parseDouble(cString.trim()); 16 double fValue = cValue*9.0/5.0+32.0; 17 fahrenheit.setText((int)fValue+""); 18 }});
19
Unit 1119 Text Field Events – Cont’d 31 public static void main(String [] args){ 32 TextFieldEventTest t = new TextFieldEventTest(); 33 t.pack(); 34 t.show(); 35 } 36 } 20 c.add(new JLabel("Fahrenheit")); 21 c.add(fahrenheit); 22 fahrenheit.addActionListener(new ActionListener() { 23 public void actionPerformed(ActionEvent ae){ 24 String fString = fahrenheit.getText(); 25 double fValue = Double.parseDouble(fString.trim()); 26 double cValue = (fValue-32.0)*5.0/9.0; 27 celcius.setText((int)cValue+""); 28 } 29 }); 30 } // end of constructor
20
Unit 1120 Review Exercises 1.Extend Example 1 by adding a Reset Total button. When the Reset Total button is pushed, the running total should be reset to zero. 2.Modify the program in Example 2 to work as a stand-alone application. 3.Modify the program in Example 3 to display its output on the application’s JFrame window. 4.Modify the program in Example 4 to use an anonymous inner class to implement the windowClosing() handler method. 5.Extend Example 5 to validate the data entered in both text fields to avoid the spurious exceptions currently raised when invalid characters are included in the input.
21
Unit 1121 Review Exercises (cont’d) 6.A student has written a working applet. Write a step-by-step procedure that guides the student to make his applet work as an application also. 7.Consider the program in Example 1. Write down all the events generated from the time the frame is displayed up to the time the user pushes the PushMe button. You may restrict your answer to the events covered in this section.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.