SlideShare una empresa de Scribd logo
1 de 20
11
Events and Applet
JAVA / Adv. OOP
22
Contents
 What is an Event?
 Events and Delegation Event Model
 Event Class, and Listener Interfaces
 Discussion on Adapter Classes
 What, Why, Purpose and benefit
 GUI Discussion
33
Events & Event Handling
 Components (AWT and Swing) generate events in response
to user actions
 Each time a user interacts with a component an event is
generated, e.g.:
 A button is pressed
 A menu item is selected
 A window is resized
 A key is pressed
 An event is an object that describes some state change in a
source
 An event informs the program about the action that must be
performed.
 The program must provide event handlers to catch and
process events. Unprocessed events are passed up
through the event hierarchy and handled by a default (do
nothing) handler
16-16-44
Listener
 Events are captured and processed by “listeners” —
objects equipped to handle a particular type of events.
 Different types of events are processed by different
types of listeners.
 Different types of “listeners” are described as interfaces:
ActionListener
ChangeListener
ItemListener
etc.
16-16-66
Listeners (cont’d)
 Event objects have useful methods. For example,
getSource returns the object that produced this event.
 A MouseEvent has methods getX, getY.
 When implementing an event listener, programmers
often use a private inner class that has access to all the
fields of the surrounding public class.
 An inner class can have constructors and private fields,
like any other class.
 A private inner class is accessible only in its outer class.
88
The Delegation Event Model
 The model provides a standard
mechanism for a source to
generate an event and send it to
a set of listeners
 A source generates events.
 Three responsibilities of a
source:
 To provide methods that allow
listeners to register and unregister
for notifications about a specific type
of event
 To generate the event
 To send the event to all registered
listeners.
Source
Listener
Listener
Listener
events
container
99
The Delegation Event Model
 A listener receives event notifications.
 Three responsibilities of a listener:
 To register to receive notifications about specific events by
calling appropriate registration method of the source.
 To implement an interface to receive events of that type.
 To unregister if it no longer wants to receive those notifications.
 The delegation event model:
 A source multicasts an event to a set of listeners.
 The listeners implement an interface to receive notifications
about that type of event.
 In effect, the source delegates the processing of the event to
one or more listeners.
1010
Event Classes Hierarchy
Object
EventObject
AWTEvent
ActionEvent ComponentEvent ItemEvent TextEvent
FocusEvent InputEvent WindowEvent
KeyEvent MouseEvent
1212
AWT Event Classes and Listener
Interfaces
Event Class Listener Interface
ActionEvent ActionListener
AdjustmentEvent AdjustmentListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
ItemEvent ItemListener
KeyEvent KeyListener
MouseEvent MouseListener, MouseMotionListener
TextEvent TextListener
WindowEvent WindowListener
1313
Semantic Event Listener
 The semantic events relate to operations on the components in the
GUI. There are 3semantic event classes.
 An ActionEvent is generated when there was an action performed on a component
such as clicking on a menu item or a button.
― Produced by Objects of Type: Buttons, Menus, Text
 An ItemEvent occurs when a component is selected or deselected.
― Produced by Objects of Type: Buttons, Menus
 An AdjustmentEvent is produced when an adjustable object, such as a scrollbar, is
adjusted.
― Produced by Objects of Type: Scrollbar
 Semantic Event Listeners
 Listener Interface: ActionListener, Method: void actionPerformed(ActionEvent e)
 Listener Interface: ItemListener, Method: void itemStateChanged (ItemEvent e)
 Listener Interface: AdjustmentListener, Method: void adjustmentValueChanged
(AdjustmentEvent e)
1414
Using the ActionListener
 Stages for Event Handling by ActionListener
 First, import event class
import java.awt.event.*;
 Define an overriding class of event type (implements
ActionListener)
 Create an event listener object
ButtonListener bt = new ButtonListener();
 Register the event listener object
b1 = new Button(“Show”);
b1.addActionListener(bt);
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
/ / Write what to be done. . .
label.setText(“Hello World!”);
}
} addActionListener
ButtonListener
action
Button Click
Event
①
②
two ways to do the same thing.
 Inner class method
 Using an anonymous inner class, you will typically use
an ActionListener class in the following manner:
ActionListener listener = new ActionListener({
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Event happened");
}
1616
OR
 Interface Method
 Implement the Listener interface in a high-level
class and use the actionPerformed method.
public class MyClass extends JFrame implements ActionListener {
...
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Event happened");
}….
}
1717
1818
MouseListener (Low-Level
Listener)
 The MouseListener interface
defines the methods to
receive mouse events.
 mouseClicked(MouseEvent me)
 mouseEntered(MouseEvent me)
 mouseExited(MouseEvent me)
 mousePressed(MouseEvent me)
 A listener must register to
receive mouse events
import javax.swing.*;
import java.awt.event.*;
class ABC extends JFrame implements MouseListener {
ABC()
{
super("Example: MouseListener");
addMouseListener(this);
setSize(250,100);
}
public void mouseClicked(MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
public void mousePressed(MouseEvent me) {
}
public void mouseReleased(MouseEvent me) {
System.out.println(me);
}
public static void main(String[] args) {
new ABC().setVisible(true);
}
}
MouseEvent
Mouse click
Adapter Classes
 Java Language rule: implement all the methods of an interface
 That way someone who wants to implement the interface but does not want or
does not know how to implement all methods, can use the adapter class
instead, and only override the methods he is interested in.
i.e.
 An adapter classes provide empty implementation of all methods
declared in an EventListener interface.
1919
2020
Adapter Classes (Low-Level Event Listener)
 The following classes show examples of listener and adapter pairs:
 package java.awt.event
 ComponentListener / ComponentAdapter
 ContainerListener / ContainerAdapter
 FocusListener / FocusAdapter
 HierarchyBoundsListener /HierarchyBoundsAdapter
 KeyListener /KeyAdapter
 MouseListener /MouseAdapter
 MouseMotionListener /MouseMotionAdapter
 WindowListener /WindowAdapter
 package java.awt.dnd
 DragSourceListener /DragSourceAdapter
 DragTargetListener /DragTargetAdapter
 package javax.swing.event
 InternalFrameListener /InternalFrameAdapter
 MouseInputListener /MouseInputAdapter
Listener Interface Style
2121
public class GoodJButtonSubclass extends JButton implements MouseListener { ...
public void mouseClicked(MouseEvent mouseEvent) { // Do nothing }
public void mouseEntered(MouseEvent mouseEvent) { // Do nothing }
public void mouseExited(MouseEvent mouseEvent) { // Do nothing }
public void mousePressed(MouseEvent mouseEvent) {
System.out.println("I'm pressed: " + mouseEvent);
}
public void mouseReleased(MouseEvent mouseEvent) { // Do nothing } ...
addMouseListener(this); ... }
Listener Inner Class Style
MouseListener mouseListener = new MouseListener() {
public void mouseClicked(MouseEvent mouseEvent) { System.out.println("I'm
clicked: " + mouseEvent); }
public void mouseEntered(MouseEvent mouseEvent) { System.out.println("I'm
entered: " + mouseEvent); }
public void mouseExited(MouseEvent mouseEvent) { System.out.println("I'm
exited: " + mouseEvent); }
public void mousePressed(MouseEvent mouseEvent) { System.out.println("I'm
pressed: " + mouseEvent); }
public void mouseReleased(MouseEvent mouseEvent) { System.out.println("I'm
released: " + mouseEvent); }
};
2222
Using Adapter Inner Class
2323
MouseListener mouseListener = new MouseAdapter() {
public void mousePressed(MouseEvent mouseEvent) {
System.out.println("I'm pressed: " + mouseEvent);
}
public void mouseReleased(MouseEvent mouseEvent)
{ System.out.println("I'm released: " + mouseEvent);
}
};
Extend inner class
from Adapter Class
2424
import java.awt.*;
import java.awt.event.*;
public class FocusAdapterExample {
Label label;
public FocusAdapterExample() {
Frame frame = new Frame();
Button Okay = new Button("Okay");
Button Cancel = new Button("Cancel");
Okay.addFocusListener(new MyFocusListener());
Cancel.addFocusListener(new MyFocusListener());
frame.add(Okay, BorderLayout.NORTH);
frame.add(Cancel, BorderLayout.SOUTH);
label = new Label();
frame.add(label, BorderLayout.CENTER);
frame.setSize(450, 400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
public class MyFocusListener extends FocusAdapter {
public void focusGained(FocusEvent fe) {
Button button = (Button) fe.getSource();
label.setText(button.getLabel());
}
}
public static void main(String[] args) {
FocusAdapterExample fc = new FocusAdapterExample();
}
}

Más contenido relacionado

La actualidad más candente

Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5
sotlsoc
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
PRN USM
 
Java event processing model in c# and java
Java  event processing model in c# and javaJava  event processing model in c# and java
Java event processing model in c# and java
Tech_MX
 
Event handling62
Event handling62Event handling62
Event handling62
myrajendra
 
openFrameworks 007 - events
openFrameworks 007 - eventsopenFrameworks 007 - events
openFrameworks 007 - events
roxlu
 

La actualidad más candente (20)

Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVA
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
 
tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handling
 
Event handling in Java(part 2)
Event handling in Java(part 2)Event handling in Java(part 2)
Event handling in Java(part 2)
 
Event handling
Event handlingEvent handling
Event handling
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 
Java Event Handling
Java Event HandlingJava Event Handling
Java Event Handling
 
Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
What is Event
What is EventWhat is Event
What is Event
 
Java event processing model in c# and java
Java  event processing model in c# and javaJava  event processing model in c# and java
Java event processing model in c# and java
 
Event handling62
Event handling62Event handling62
Event handling62
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
Lecture8 oopj
Lecture8 oopjLecture8 oopj
Lecture8 oopj
 
A Series of Fortunate Events - Symfony Camp Sweden 2014
A Series of Fortunate Events - Symfony Camp Sweden 2014A Series of Fortunate Events - Symfony Camp Sweden 2014
A Series of Fortunate Events - Symfony Camp Sweden 2014
 
09events
09events09events
09events
 
Advance Java Programming (CM5I) 2.Swing
Advance Java Programming (CM5I) 2.SwingAdvance Java Programming (CM5I) 2.Swing
Advance Java Programming (CM5I) 2.Swing
 
GUI (graphical user interface)
GUI (graphical user interface)GUI (graphical user interface)
GUI (graphical user interface)
 
openFrameworks 007 - events
openFrameworks 007 - eventsopenFrameworks 007 - events
openFrameworks 007 - events
 

Similar a Java gui event

ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
udithaisur
 
Chapter11 graphical components
Chapter11 graphical componentsChapter11 graphical components
Chapter11 graphical components
Arifa Fatima
 
Java session11
Java session11Java session11
Java session11
Niit Care
 

Similar a Java gui event (20)

Unit 6 Java
Unit 6 JavaUnit 6 Java
Unit 6 Java
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
 
Synapseindia dotnet development chapter 14 event-driven programming
Synapseindia dotnet development  chapter 14 event-driven programmingSynapseindia dotnet development  chapter 14 event-driven programming
Synapseindia dotnet development chapter 14 event-driven programming
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 
event handling new.ppt
event handling new.pptevent handling new.ppt
event handling new.ppt
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
 
EventBus for Android
EventBus for AndroidEventBus for Android
EventBus for Android
 
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing ButtonsJAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Androd Listeners
Androd ListenersAndrod Listeners
Androd Listeners
 
Chapter11 graphical components
Chapter11 graphical componentsChapter11 graphical components
Chapter11 graphical components
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
 
Java session11
Java session11Java session11
Java session11
 
event_handling.ppt
event_handling.pptevent_handling.ppt
event_handling.ppt
 
Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.
 
File Handling
File HandlingFile Handling
File Handling
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Java gui event

  • 2. 22 Contents  What is an Event?  Events and Delegation Event Model  Event Class, and Listener Interfaces  Discussion on Adapter Classes  What, Why, Purpose and benefit  GUI Discussion
  • 3. 33 Events & Event Handling  Components (AWT and Swing) generate events in response to user actions  Each time a user interacts with a component an event is generated, e.g.:  A button is pressed  A menu item is selected  A window is resized  A key is pressed  An event is an object that describes some state change in a source  An event informs the program about the action that must be performed.  The program must provide event handlers to catch and process events. Unprocessed events are passed up through the event hierarchy and handled by a default (do nothing) handler
  • 4. 16-16-44 Listener  Events are captured and processed by “listeners” — objects equipped to handle a particular type of events.  Different types of events are processed by different types of listeners.  Different types of “listeners” are described as interfaces: ActionListener ChangeListener ItemListener etc.
  • 5. 16-16-66 Listeners (cont’d)  Event objects have useful methods. For example, getSource returns the object that produced this event.  A MouseEvent has methods getX, getY.  When implementing an event listener, programmers often use a private inner class that has access to all the fields of the surrounding public class.  An inner class can have constructors and private fields, like any other class.  A private inner class is accessible only in its outer class.
  • 6. 88 The Delegation Event Model  The model provides a standard mechanism for a source to generate an event and send it to a set of listeners  A source generates events.  Three responsibilities of a source:  To provide methods that allow listeners to register and unregister for notifications about a specific type of event  To generate the event  To send the event to all registered listeners. Source Listener Listener Listener events container
  • 7. 99 The Delegation Event Model  A listener receives event notifications.  Three responsibilities of a listener:  To register to receive notifications about specific events by calling appropriate registration method of the source.  To implement an interface to receive events of that type.  To unregister if it no longer wants to receive those notifications.  The delegation event model:  A source multicasts an event to a set of listeners.  The listeners implement an interface to receive notifications about that type of event.  In effect, the source delegates the processing of the event to one or more listeners.
  • 8. 1010 Event Classes Hierarchy Object EventObject AWTEvent ActionEvent ComponentEvent ItemEvent TextEvent FocusEvent InputEvent WindowEvent KeyEvent MouseEvent
  • 9. 1212 AWT Event Classes and Listener Interfaces Event Class Listener Interface ActionEvent ActionListener AdjustmentEvent AdjustmentListener ComponentEvent ComponentListener ContainerEvent ContainerListener FocusEvent FocusListener ItemEvent ItemListener KeyEvent KeyListener MouseEvent MouseListener, MouseMotionListener TextEvent TextListener WindowEvent WindowListener
  • 10. 1313 Semantic Event Listener  The semantic events relate to operations on the components in the GUI. There are 3semantic event classes.  An ActionEvent is generated when there was an action performed on a component such as clicking on a menu item or a button. ― Produced by Objects of Type: Buttons, Menus, Text  An ItemEvent occurs when a component is selected or deselected. ― Produced by Objects of Type: Buttons, Menus  An AdjustmentEvent is produced when an adjustable object, such as a scrollbar, is adjusted. ― Produced by Objects of Type: Scrollbar  Semantic Event Listeners  Listener Interface: ActionListener, Method: void actionPerformed(ActionEvent e)  Listener Interface: ItemListener, Method: void itemStateChanged (ItemEvent e)  Listener Interface: AdjustmentListener, Method: void adjustmentValueChanged (AdjustmentEvent e)
  • 11. 1414 Using the ActionListener  Stages for Event Handling by ActionListener  First, import event class import java.awt.event.*;  Define an overriding class of event type (implements ActionListener)  Create an event listener object ButtonListener bt = new ButtonListener();  Register the event listener object b1 = new Button(“Show”); b1.addActionListener(bt); class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { / / Write what to be done. . . label.setText(“Hello World!”); } } addActionListener ButtonListener action Button Click Event ① ②
  • 12. two ways to do the same thing.  Inner class method  Using an anonymous inner class, you will typically use an ActionListener class in the following manner: ActionListener listener = new ActionListener({ public void actionPerformed(ActionEvent actionEvent) { System.out.println("Event happened"); } 1616
  • 13. OR  Interface Method  Implement the Listener interface in a high-level class and use the actionPerformed method. public class MyClass extends JFrame implements ActionListener { ... public void actionPerformed(ActionEvent actionEvent) { System.out.println("Event happened"); }…. } 1717
  • 14. 1818 MouseListener (Low-Level Listener)  The MouseListener interface defines the methods to receive mouse events.  mouseClicked(MouseEvent me)  mouseEntered(MouseEvent me)  mouseExited(MouseEvent me)  mousePressed(MouseEvent me)  A listener must register to receive mouse events import javax.swing.*; import java.awt.event.*; class ABC extends JFrame implements MouseListener { ABC() { super("Example: MouseListener"); addMouseListener(this); setSize(250,100); } public void mouseClicked(MouseEvent me) { } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } public void mousePressed(MouseEvent me) { } public void mouseReleased(MouseEvent me) { System.out.println(me); } public static void main(String[] args) { new ABC().setVisible(true); } } MouseEvent Mouse click
  • 15. Adapter Classes  Java Language rule: implement all the methods of an interface  That way someone who wants to implement the interface but does not want or does not know how to implement all methods, can use the adapter class instead, and only override the methods he is interested in. i.e.  An adapter classes provide empty implementation of all methods declared in an EventListener interface. 1919
  • 16. 2020 Adapter Classes (Low-Level Event Listener)  The following classes show examples of listener and adapter pairs:  package java.awt.event  ComponentListener / ComponentAdapter  ContainerListener / ContainerAdapter  FocusListener / FocusAdapter  HierarchyBoundsListener /HierarchyBoundsAdapter  KeyListener /KeyAdapter  MouseListener /MouseAdapter  MouseMotionListener /MouseMotionAdapter  WindowListener /WindowAdapter  package java.awt.dnd  DragSourceListener /DragSourceAdapter  DragTargetListener /DragTargetAdapter  package javax.swing.event  InternalFrameListener /InternalFrameAdapter  MouseInputListener /MouseInputAdapter
  • 17. Listener Interface Style 2121 public class GoodJButtonSubclass extends JButton implements MouseListener { ... public void mouseClicked(MouseEvent mouseEvent) { // Do nothing } public void mouseEntered(MouseEvent mouseEvent) { // Do nothing } public void mouseExited(MouseEvent mouseEvent) { // Do nothing } public void mousePressed(MouseEvent mouseEvent) { System.out.println("I'm pressed: " + mouseEvent); } public void mouseReleased(MouseEvent mouseEvent) { // Do nothing } ... addMouseListener(this); ... }
  • 18. Listener Inner Class Style MouseListener mouseListener = new MouseListener() { public void mouseClicked(MouseEvent mouseEvent) { System.out.println("I'm clicked: " + mouseEvent); } public void mouseEntered(MouseEvent mouseEvent) { System.out.println("I'm entered: " + mouseEvent); } public void mouseExited(MouseEvent mouseEvent) { System.out.println("I'm exited: " + mouseEvent); } public void mousePressed(MouseEvent mouseEvent) { System.out.println("I'm pressed: " + mouseEvent); } public void mouseReleased(MouseEvent mouseEvent) { System.out.println("I'm released: " + mouseEvent); } }; 2222
  • 19. Using Adapter Inner Class 2323 MouseListener mouseListener = new MouseAdapter() { public void mousePressed(MouseEvent mouseEvent) { System.out.println("I'm pressed: " + mouseEvent); } public void mouseReleased(MouseEvent mouseEvent) { System.out.println("I'm released: " + mouseEvent); } };
  • 20. Extend inner class from Adapter Class 2424 import java.awt.*; import java.awt.event.*; public class FocusAdapterExample { Label label; public FocusAdapterExample() { Frame frame = new Frame(); Button Okay = new Button("Okay"); Button Cancel = new Button("Cancel"); Okay.addFocusListener(new MyFocusListener()); Cancel.addFocusListener(new MyFocusListener()); frame.add(Okay, BorderLayout.NORTH); frame.add(Cancel, BorderLayout.SOUTH); label = new Label(); frame.add(label, BorderLayout.CENTER); frame.setSize(450, 400); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } public class MyFocusListener extends FocusAdapter { public void focusGained(FocusEvent fe) { Button button = (Button) fe.getSource(); label.setText(button.getLabel()); } } public static void main(String[] args) { FocusAdapterExample fc = new FocusAdapterExample(); } }

Notas del editor

  1. A listener is an object.
  2. ActionListener specifies one method: void actionPerformed(ActionEvent e);
  3. Inner classes are not in the AP subset.
  4. Inner classes contradict the main OOP philosophy.