Presentation is loading. Please wait.

Presentation is loading. Please wait.

Event-Driven Programming

Similar presentations


Presentation on theme: "Event-Driven Programming"— Presentation transcript:

1 Event-Driven Programming
Learning Outcomes Extend the example programs to write more interesting GUI Use nested classes and adapter classes to write medium-sized applications. Example 1: Handling Button Events Example 2: Handling Mouse Events Example 3: Handling Keyboard Events Self-check Exercise 1 Adapter Classes Example 4: Handling Window Events Example 5: Handling Text Field Events Self-check Exercise 2 Exercises Unit 12

2 Handling Button Events
This example builds on Example 2 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: Unit 12

3 Example 1: Button Events
1 import java.awt.*; 2 import java.awt.event.*; 3 class ButtonEventTest extends AddingComponents implements ActionListener{ private int sum; public ButtonEventTest() { button.addActionListener(this); } public void actionPerformed(ActionEvent ae) { sum += 1; textField.setText(sum+""); Toolkit.getDefaultToolkit().beep(); } public static void main(String args []) { new ButtonEventTest(); } 17 } Unit 12

4 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. Unit 12

5 Example 2: Mouse Events 1 import java.awt.*; import java.awt.event.*;
2 public class MouseEventTest extends ButtonEventTest{ public MouseEventTest(){ class LightUpListener extends MouseAdapter { public void mouseEntered(MouseEvent e) { Component c = (Component)e.getSource(); c.setBackground(Color.green); } public void mouseExited(MouseEvent e) { Component c = (Component)e.getSource(); c.setBackground(Color.red); } } MouseListener listener = new LightUpListener(); button.addMouseListener(listener); textField.addMouseListener(listener); cp.addMouseListener(listener); } public static void main(String[] args) { new MouseEventTest(); } 22 } Unit 12

6 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. Unit 12

7 Example 3: 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){ showStatus("Key Down"); 8 } 9 public void keyReleased(KeyEvent ke){showStatus("Key Up"); } public void keyTyped(KeyEvent ke){ msg += ke.getKeyChar(); repaint(); } public void init(){ requestFocus(); addKeyListener(this); } public void paint(Graphics g){ g.drawString(msg,startX,startY); } 21 } Unit 12

8 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. Adapter classes provide empty implementations for the handlers. Most listener interfaces with two or more methods have matching adapter classes. Unit 12

9 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. Unit 12

10 Example 4: 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() { super("Window Event Test"); setSize(300,300); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we) { WindowEventTest obj = WindowEventTest.this; int result = JOptionPane.showConfirmDialog(obj, msg); if (result == JOptionPane.YES_OPTION) System.exit(0); else { int keepOpen = WindowConstants.DO_NOTHING_ON_CLOSE; setDefaultCloseOperation(keepOpen); } }}); } public static void main(String args [] ) { WindowEventTest wt = new WindowEventTest(); wt.setVisible(true); } 22 } Unit 12

11 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. Unit 12

12 Example 5: 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(){ c.setLayout(new FlowLayout()); c.add(new JLabel("Celcius")); c.add(celcius); celcius.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae){ String cString = celcius.getText(); double cValue = Double.parseDouble(cString.trim()); double fValue = cValue*9.0/ ; fahrenheit.setText((int)fValue+""); } }); // code continues next page Unit 12

13 Text Field Events – Cont’d
c.add(new JLabel("Fahrenheit")); c.add(fahrenheit); fahrenheit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae){ String fString = fahrenheit.getText(); double fValue = Double.parseDouble(fString.trim()); double cValue = (fValue-32.0)*5.0/9.0; celcius.setText((int)cValue+""); } }); 30 } // end of constructor 31 public static void main(String [] args){ TextFieldEventTest t = new TextFieldEventTest(); t.pack(); t.show(); 35 } 36 } Unit 12

14 Review Exercises Extend Example 1 by adding a Reset Total button. When the Reset Total button is pushed, the running total should be reset to zero. Modify the program in Example 2 to work as a stand-alone application. Modify the program in Example 3 to display its output on the application’s JFrame window. Modify the program in Example 4 to use an anonymous inner class to implement the windowClosing() handler method. 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. Unit 12

15 Review Exercises (cont’d)
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. 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. Unit 12


Download ppt "Event-Driven Programming"

Similar presentations


Ads by Google