Anda di halaman 1dari 17

OOP (TAB2053)

GUI Listener

UTP2008

Event Listening & Handling

What happens if you try to click the Exit button from the
earlier example? Is there any response after we click the
button?
Answer: No. Because we have not yet registered the
listener and handler to the event source!

UTP2008

Event Listening & Handling


1.

CLICK EVENT

2.

JV
M

ActionListener
3.
4.
5.

Take action!!!!
Do something!!!

Event source automatically generates an event


when invoked.Examples:
a.
A button click or selecting a menu item
ActionEvent
b.
A mouse click or movement
MouseEvent
c.
A frame is closed or iconified
WindowEvent
Unfortunately, the components (both containers
and widgets) are unable to detect WHEN these
events are invoked unless we do something
We must add a listener (register event listener) to
the GUI component.
How?
Use addActionListener() method.
We also need to tell the GUI component how to
respond if it hears the event. How?
a.
Create one or more handlers.
b.
Pass the handler as a parameter in
addActionListener() method. Example:
addActionListener(myEventHandler)

UTP2008

Event Listening & Handling


Before the coding

After the coding

What should I listen


to?

Oh.. I should listen to


this button click

If I hear it, then what


should I do?

JAVA

UTP2008

Then, I must
immediately execute
the handler.

JAVA

Quiz yourself
1. What is an event source? Give a few examples.
2. What is an event? Give a few examples.
3. Why do we add listeners to the components?
4. Who should listen to whose event?
5. Why dont we make the event source automatically listens to the
event instead of using methods of adding the listener explicity?
6. What should the program respond to the event? Take action?
What action? How?
7. What is the handler, really?

UTP2008

Event Handler
1. The event handler object is instantiated from the handler
class that implements the listener interface.
2. The handler class must contain all overriding method for the
interface, such as public void actionPerformed(ActionEvent event){}

UTP2008

<<interface>>
Interface01
+method01():void

<<interface>>
ActionListener
+actionPerformed(ActionEvent event):void

MyClass
+method01():void

MyClass
+actionPerformed(ActionEvent event):void

Generic Interface
Implementation

Implementing
ActionListener inteface

Event Handler
Two flavors of implementations:
GUI and handler in the same class.
GUI and handler in separate classes.
<<interface>>
ActionListener
+actionPerformed(ActionEvent event):void

<<interface>>
ActionListener
+actionPerformed(ActionEvent event):void

MyGUIClass
+actionPerformed(ActionEvent event):void

MyActionHandler
+actionPerformed(ActionEvent event):void

<<uses>>

MyGUI
+method1():void

UTP2008

Event Handling
There can be one or
multiple handlers for
one single event.

(Image & content taken from


Sun Microsystem SL275 SE6
textbook)

UTP2008

1.
2.
3.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

4.
5.
6.

public class MyActiveGUI implements ActionListener {


JButton button1;
JPanel panel;

7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.

public MyActiveGUI() {
button1 = new JButton(Exit);
button1.addActionListener(this);
panel = new JPanel();
panel.add(button1);
}
JPanel getPanel() { }
public void actionPerformed(ActionEvent ae) {
JButton but = (JButton) ae.getSource();
String labelOnBut = but.getText();
if (labelOnBut.equals(Exit)) {
System.out.println(Program terminated.");
System.exit(1);
}
}

Abide to a contract:
You will be recognized as a
listener.
You will get notification.
But you must implement a
method that
acts upon the notification.

Refers to the current object. The


current object is the handler
because it implements the
ActionListener.

This method you must


define when you
implements ActionListener

UTP2008

Adding Behavior to More than One Buttons


What should I do to make the program respond to
different buttons when clicked?

UTP2008

10

Adding Behavior to More than One Buttons


1.
2.
3.
4.

import
import
import
import

5.

public class MultipleButtons implements


ActionListener {
JFrame myFrame;
Container myPane;
JPanel myPanel;
JButton loginButton;
JButton clearButton;
JButton exitButton;

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

javax.swing.*;
javax.swing.JOptionPane;
java.awt.*;
java.awt.event.*;

public MultipleButtons(){
myFrame = new JFrame("Event Handling
Demo");
myPane = myFrame.getContentPane();
myPanel = new JPanel();
loginButton = new JButton("Login");
loginButton.addActionListener(this);
clearButton = new JButton("Clear");
clearButton.addActionListener(this);
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
}
public void createAndShowGUI(){
myPanel.add(loginButton);
myPanel.add(clearButton);
myPanel.add(exitButton);
myPane.add(myPanel,BorderLayout.PAGE_END);
myFrame.pack();
myFrame.setVisible(true);
}

UTP2008

33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.

54.
55.
56.
57.

public static void main(String [] args){


MultipleButtons myDemo = new
MultipleButtons();
myDemo.createAndShowGUI();
}
{

public void actionPerformed(ActionEvent ae)


JButton but = (JButton) ae.getSource();
String labelOnBut = but.getText();
if (labelOnBut.equals("Login")) {
//perform login function

JOptionPane.showMessageDialog(myFrame,"Login
successful");
}
if (labelOnBut.equals("Clear")) {
//perform textfield and password
field clearing function
JOptionPane.showMessageDialog(myFrame,"Please
key in again.");
}
if (labelOnBut.equals("Exit")) {
int response =
JOptionPane.showConfirmDialog(myFrame, "Are you
sure?", "Confirmation",
JOptionPane.YES_NO_OPTION);
if (response==0)System.exit(0);
}
}
}

11

getSource() method
1.

Example:
JButton but = (JButton) ae.getSource();

2.

3.

getSource() returns a Component object.


. Component is a general data type, eg. Human is a general
data type for student.
. But unfortunately too general. Hence we need to cast to
specify further.
Example:
(JButton) cast the datatype to another type JButton.

UTP2008

12

Adding Behavior to Widget


1.
2.

public void actionPerformed(ActionEvent ae)


{

3.

Object comp = ae.getSource();

4.
5.
6.
7.
8.

if (comp instanceof JButton)


{
JButton but = (JButton) comp;
if (but == button1) {
System.out.println("Entered: " +
textField.getText()); }
}

9.
10.

UTP2008

13

Adding Multiple Behaviors to One Component


1.

We can add multiple behaviors to one component.

2.

This is done by simply implementing more interface and adding more handlers.

Category Interface

Methods to be implemented

Action

actionPerformed(ActionEvent)

Item

ActionListener
ItemListener

Mouse

itemStateChanged(ItemEvent)

MouseListener

mousePressed(MouseEvent)

mouseReleased(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mouseClicked(MouseEvent)
Mouse motion

MouseMotionListener

mouseDragged(MouseEvent)

mouseMoved(MouseEvent)
Key

KeyListener

keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)

Mouse wheel
Text
UTP2008

MouseWheelListener

TextListener

mouseWheelMoved(MouseWheelEvent e)

textValueChanged(TextEvent)
14

Adding Multiple Behaviors to One Component

The above GUI listens to the mouse motion and mouse clicks.

UTP2008

15

Adding Multiple Behaviors to One Component


1.

import javax.swing.*;

25.

public void mouseEntered(MouseEvent e) {

2.

import java.awt.*;

26.

String s = "The mouse entered";

3.

import java.awt.event.*;

27.

tf.setText(s);

28.

4.

public class MultipleBehaviors implements MouseMotionListener, MouseListener {

5.

private JFrame f;

29.

public void mouseExited(MouseEvent e) {

6.

private JTextField tf;

30.

String s = "The mouse has left the building";

31.

tf.setText(s);

32.

33.

// Unused MouseMotionListener method.

7.

public MultipleBehaviors() {

8.

f = new JFrame("Two listeners example");

9.

tf = new JTextField(30);

10.

34.

public void mouseMoved(MouseEvent e) { }

11.

public void launchFrame() {

35.

// Unused MouseListener methods.

12.

JLabel label = new JLabel("Click and drag the mouse");

36.

public void mousePressed(MouseEvent e) { }

13.

f.add(label, BorderLayout.NORTH);

37.

public void mouseClicked(MouseEvent e) { }

14.

f.add(tf, BorderLayout.SOUTH);

38.

public void mouseReleased(MouseEvent e) { }

15.

f.addMouseMotionListener(this);

16.

f.addMouseListener(this);

39.

public static void main(String args[]) {

17.

f.setSize(300, 200);

40.

MultipleBehaviors two = new MultipleBehaviors();

18.

f.setVisible(true);

41.

two.launchFrame();

42.

43.

19.

20.

// These are MouseMotionListener events

21.

public void mouseDragged(MouseEvent e) {

22.

String s = "Mouse dragging: X = " + e.getX() + " Y = " + e.getY();

23.

tf.setText(s);

24.

UTP2008

16

Summary of event listening and handling


Steps to do:
1. Event listening and handling are contained in java.awt.event,
hence not to forget the need to import the package into our code.
Identify the event source.
2. Create the event handler(s).
3. Register listener to the GUI component (usually the event source
itself).
4. Pass the event handler as the parameter in the addActionListener
method.

UTP2008

17