SlideShare a Scribd company logo
1
CSE 331
More Events
(Mouse, Keyboard, Window,
Focus, Change, Document ...)
slides created by Marty Stepp
based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
http://www.cs.washington.edu/331/
2
Mouse events
• Usage of mouse events:
 listen to clicks / movement of mouse in a component
 respond to mouse activity with appropriate actions
 create interactive programs that are driven by mouse activity
• Usage of keyboard events:
 listen and respond to keyboard activity within a GUI component
 control onscreen drawn characters and simulate text input
• Key and mouse events are called low-level
events because they are close to the
hardware interactions the user performs.
3
MouseListener interface
public interface MouseListener {
public void mouseClicked(MouseEvent event);
public void mouseEntered(MouseEvent event);
public void mouseExited(MouseEvent event);
public void mousePressed(MouseEvent event);
public void mouseReleased(MouseEvent event);
}
• Many AWT/Swing components have this method:
 public void addMouseListener(MouseListener ml)
• Mouse listeners are often added to custom components and
drawing canvases to respond to clicks and other mouse actions.
4
Implementing listener
public class MyMouseListener implements MouseListener {
public void mouseClicked(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
public void mousePressed(MouseEvent event) {
System.out.println("You pressed the button!");
}
public void mouseReleased(MouseEvent event) {}
}
// elsewhere,
myComponent.addMouseListener(new MyMouseListener());
 Problem: Tedious to implement entire interface when only partial
behavior is wanted / needed.
5
Pattern: Adapter
an object that fits another object into a given interface
6
Adapter pattern
• Problem: We have an object that contains the functionality we
need, but not in the way we want to use it.
 Cumbersome / unpleasant to use. Prone to bugs.
• Example:
 We want to write one or two mouse input methods.
 Java makes us implement an interface full of methods we don't want.
• Solution:
 Provide an adapter class that connects into the setup we must talk to
(GUI components) but exposes to us the interface we prefer (only have
to write one or two methods).
7
Event adapters
• event adapter: A class with empty implementations of all of a given
listener interface's methods.
 examples: MouseAdapter, KeyAdapter, FocusAdapter
 Extend MouseAdapter; override methods you want to implement.
• Don't have to type in empty methods for the ones you don't want!
 an example of the Adapter design pattern
 Why is there no ActionAdapter for ActionListener?
8
An abstract event adapter
// This class exists in package java.awt.event.
// An empty implementation of all MouseListener methods.
public abstract class MouseAdapter implements MouseListener {
public void mousePressed(MouseEvent event) {}
public void mouseReleased(MouseEvent event) {}
public void mouseClicked(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
}
 Now classes can extend MouseAdapter rather than
implementing MouseListener.
• client gets the complete mouse listener interface it wants
• implementer gets to write just the few mouse methods they want
• Why did Sun include MouseListener? Why not just the adapter?
9
Abstract classes
• abstract class: A hybrid between an interface and a class.
 Defines a superclass type that can contain method declarations (like an
interface) and/or method bodies (like a class).
 Like interfaces, abstract classes that cannot be instantiated
(cannot use new to create any objects of their type).
• What goes in an abstract class?
 Implementation of common state and behavior that will be inherited
by subclasses (parent class role)
 Declare generic behavior for subclasses to implement (interface role)
10
Abstract class syntax
// declaring an abstract class
public abstract class name {
...
// declaring an abstract method
// (any subclass must implement it)
public abstract type name(parameters);
}
• A class can be abstract even if it has no abstract methods
• You can create variables (but not objects) of the abstract type
11
Writing an adapter
public class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent event) {
System.out.println("You pressed the button!");
}
}
// elsewhere,
myComponent.addMouseListener(new MyMouseAdapter());
12
Abstract class vs. interface
• Why do both interfaces and abstract classes exist in Java?
 An abstract class can do everything an interface can do and more.
 So why would someone ever use an interface?
• Answer: Java has only single inheritance.
 can extend only one superclass
 can implement many interfaces
 Having interfaces allows a class to be part of a hierarchy
(polymorphism) without using up its inheritance relationship.
13
MouseEvent properties
• MouseEvent
 public static int BUTTON1_MASK,
BUTTON2_MASK, BUTTON3_MASK,
CTRL_MASK, ALT_MASK, SHIFT_MASK
 public int getClickCount()
 public Point getPoint()
 public int getX(), getY()
 public Object getSource()
 public int getModifiers() // use *_MASK with this
• SwingUtilities
 static void isLeftMouseButton(MouseEvent event)
 static void isRightMouseButton(MouseEvent event)
14
Using MouseEvent
public class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent event) {
Object source = event.getSource();
if (source == button && event.getX() < 10) {
JOptionPane.showMessageDialog(null,
"You clicked the left edge!");
}
}
}
15
Mouse motion
public interface MouseMotionListener {
public void mouseDragged(MouseEvent event);
public void mouseMoved(MouseEvent event);
}
• For some reason Java separates mouse input into many interfaces.
 The second focuses on the movement of the mouse cursor.
• Many AWT/Swing components have this method:
 public void addMouseMotionListener(
MouseMotionListener ml)
• The abstract MouseMotionAdapter class provides empty
implementations of both methods if you just want to override one.
16
Mouse wheel scrolling
public interface MouseWheelListener {
public void mouseWheelMoved(MouseWheelEvent event);
}
 The third mouse event interface focuses on the rolling of the mouse's
scroll wheel button.
• Many AWT/Swing components have this method:
 public void addMouseWheelListener(
MouseWheelListener ml)
17
Mouse input listener
// import javax.swing.event.*;
public interface MouseInputListener
extends MouseListener, MouseMotionListener,
MouseWheelListener {}
• The MouseInputListener interface combines all kinds of
mouse input into a single interface that you can implement.
• The MouseInputAdapter class includes empty implementations
for all methods from all mouse input interfaces, allowing the same
listener object to listen to mouse clicks, movement, and/or wheel
events.
18
Mouse input example
public class MyMouseInputAdapter extends MouseInputAdapter {
public void mousePressed(MouseEvent event) {
System.out.println("Mouse was pressed");
}
public void mouseDragged(MouseEvent event) {
Point p = event.getPoint();
System.out.println("Mouse is at " + p);
}
}
...
// using the listener
MyMouseInputAdapter adapter = new MyMouseInputAdapter();
myPanel.addMouseListener(adapter);
myPanel.addMouseMotionListener(adapter);
19
Keyboard Events
20
KeyListener interface
public interface KeyListener {
public void keyPressed(KeyEvent event);
public void keyReleased(KeyEvent event);
public void keyTyped(KeyEvent event);
}
• Many AWT/Swing components have this method:
 public void addKeyListener(KeyListener kl)
• The abstract class KeyAdapter implements all KeyListener
methods with empty bodies.
21
KeyEvent objects
 // what key code was pressed?
public static int VK_A, VK_B, ..., VK_Z,
VK_0, ... VK_9,
VK_F1, ... VK_F10,
VK_UP, VK_LEFT, ...,
VK_TAB, VK_SPACE, VK_ENTER, ...
(one for almost every key)
 // Were any modifier keys held down?
public static int CTRL_MASK, ALT_MASK, SHIFT_MASK
 public char getKeyChar()
 public int getKeyCode() // use VK_* with this
 public Object getSource()
 public int getModifiers() // use *_MASK with this
22
Key event example
public class PacManKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent event) {
char keyChar = event.getKeyChar();
int keyCode = event.getKeyCode();
if (keyCode == KeyEvent.VK_RIGHT) {
pacman.setX(pacman.getX() + 1);
} else if (keyChar == 'Q') {
quit();
}
}
}
// elsewhere,
myJFrame.addKeyListener(new PacKeyListener());
23
Other Kinds of Events
24
Focus events
public interface FocusListener {
public void focusGained(FocusEvent event);
public void focusLost(FocusEvent event);
}
• focus: The current target of keyboard input.
 A focus event occurs when the keyboard cursor enters or exits a
component, signifying the start/end of typing on that control.
• Many AWT/Swing components have this method:
 public void addFocusListener(FocusListener kl)
• The abstract class FocusAdapter implements all
FocusListener methods with empty bodies.
25
Window events
public interface WindowListener {
public void windowActivated(WindowEvent event);
public void windowClosed(WindowEvent event);
public void windowClosing(WindowEvent event);
public void windowDeactivated(WindowEvent event);
public void windowDeiconified(WindowEvent event);
public void windowIconified(WindowEvent event);
public void windowOpened(WindowEvent event);
}
• A JFrame object has this method:
 public void addWindowListener(WindowListener wl)
• The abstract class WindowAdapter implements all
WindowListener methods with empty bodies.
26
Change events
public interface ChangeListener {
public void stateChanged(ChangeEvent event);
}
• These events occur when some kind of state of a given component
changes. Not used by all components, but essential for some.
• JSpinner, JSlider, JTabbedPane, JColorChooser,
JViewPort, and other components have this method:
 public void addChangeListener(ChangeListener cl)
27
Component events
public interface ComponentListener {
public void componentHidden(ComponentEvent event);
public void componentMoved(ComponentEvent event);
public void componentResized(ComponentEvent event);
public void componentShown(ComponentEvent event);
}
• These events occur when a layout manager reshapes a component
or when it is set to be visible or invisible.
• Many AWT/Swing components have this method:
 public void addComponentListener(ComponentListener cl)
• The abstract class ComponentAdapter implements all
ComponentListener methods with empty bodies.
28
JList/JTree select events
public interface ListSelectionListener {
public void valueChanged(ListSelectionEvent event);
}
public interface TreeSelectionListener {
public void valueChanged(TreeSelectionEvent event);
}
• These events occur when a user changes the
element(s) selected within a JList or JTree.
• The JList component has this method:
 public void addListSelectionListener(
ListSelectionListener lsl)
• The JTree component has this method:
 public void addTreeSelectionListener(
TreeSelectionListener tsl)
29
Document events
public interface DocumentListener {
public void changedUpdate(DocumentEvent event);
public void insertUpdate(DocumentEvent event);
public void removeUpdate(DocumentEvent event);
}
• These events occur when the contents of a text component (e.g.
JTextField or JTextArea) change.
• Such components have this method:
 public Document getDocument()
• And a Document object has this method:
 public void addDocumentListener(DocumentListener cl)
• And yes, there is a DocumentAdapter .
Ad

More Related Content

Similar to java - topic (event handling notes )1.ppt (20)

JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdfJEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
MarlouFelixIIICunana
 
Flash Lite & Touch: build an iPhone-like dynamic list
Flash Lite & Touch: build an iPhone-like dynamic listFlash Lite & Touch: build an iPhone-like dynamic list
Flash Lite & Touch: build an iPhone-like dynamic list
Small Screen Design
 
09events
09events09events
09events
Waheed Warraich
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
raksharao
 
Unit 6 Java
Unit 6 JavaUnit 6 Java
Unit 6 Java
arnold 7490
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
sharanyak0721
 
Event Handling in Java as per university
Event Handling in Java as per universityEvent Handling in Java as per university
Event Handling in Java as per university
Sanjay Kumar
 
Gui
GuiGui
Gui
Sardar Alam
 
Top 3 SWT Exceptions
Top 3 SWT ExceptionsTop 3 SWT Exceptions
Top 3 SWT Exceptions
Lakshmi Priya
 
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
Jyothishmathi Institute of Technology and Science Karimnagar
 
How to use Listener Class in Flutter.pptx
How to use Listener Class in Flutter.pptxHow to use Listener Class in Flutter.pptx
How to use Listener Class in Flutter.pptx
RubenGray1
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
shanmuga rajan
 
EventHandling in object oriented programming
EventHandling in object oriented programmingEventHandling in object oriented programming
EventHandling in object oriented programming
Parameshwar Maddela
 
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
nehakumari0xf
 
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
kashyapneha2809
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
Advance java for bscit
Advance java for bscitAdvance java for bscit
Advance java for bscit
YogeshDhamke2
 
Ajp notes-chapter-03
Ajp notes-chapter-03Ajp notes-chapter-03
Ajp notes-chapter-03
Ankit Dubey
 
Eclipse Training - SWT & JFace
Eclipse Training - SWT & JFaceEclipse Training - SWT & JFace
Eclipse Training - SWT & JFace
Luca D'Onofrio
 
Developing social simulations with UbikSim
Developing social simulations with UbikSimDeveloping social simulations with UbikSim
Developing social simulations with UbikSim
Emilio Serrano
 
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdfJEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
MarlouFelixIIICunana
 
Flash Lite & Touch: build an iPhone-like dynamic list
Flash Lite & Touch: build an iPhone-like dynamic listFlash Lite & Touch: build an iPhone-like dynamic list
Flash Lite & Touch: build an iPhone-like dynamic list
Small Screen Design
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
raksharao
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
sharanyak0721
 
Event Handling in Java as per university
Event Handling in Java as per universityEvent Handling in Java as per university
Event Handling in Java as per university
Sanjay Kumar
 
Top 3 SWT Exceptions
Top 3 SWT ExceptionsTop 3 SWT Exceptions
Top 3 SWT Exceptions
Lakshmi Priya
 
How to use Listener Class in Flutter.pptx
How to use Listener Class in Flutter.pptxHow to use Listener Class in Flutter.pptx
How to use Listener Class in Flutter.pptx
RubenGray1
 
EventHandling in object oriented programming
EventHandling in object oriented programmingEventHandling in object oriented programming
EventHandling in object oriented programming
Parameshwar Maddela
 
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
nehakumari0xf
 
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
kashyapneha2809
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
Advance java for bscit
Advance java for bscitAdvance java for bscit
Advance java for bscit
YogeshDhamke2
 
Ajp notes-chapter-03
Ajp notes-chapter-03Ajp notes-chapter-03
Ajp notes-chapter-03
Ankit Dubey
 
Eclipse Training - SWT & JFace
Eclipse Training - SWT & JFaceEclipse Training - SWT & JFace
Eclipse Training - SWT & JFace
Luca D'Onofrio
 
Developing social simulations with UbikSim
Developing social simulations with UbikSimDeveloping social simulations with UbikSim
Developing social simulations with UbikSim
Emilio Serrano
 

Recently uploaded (20)

Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...
Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...
Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...
National Information Standards Organization (NISO)
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Contact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: OptometryContact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: Optometry
MushahidRaza8
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Introduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdfIntroduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdf
james5028
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Contact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: OptometryContact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: Optometry
MushahidRaza8
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
Introduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdfIntroduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdf
james5028
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Ad

java - topic (event handling notes )1.ppt

  • 1. 1 CSE 331 More Events (Mouse, Keyboard, Window, Focus, Change, Document ...) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/
  • 2. 2 Mouse events • Usage of mouse events:  listen to clicks / movement of mouse in a component  respond to mouse activity with appropriate actions  create interactive programs that are driven by mouse activity • Usage of keyboard events:  listen and respond to keyboard activity within a GUI component  control onscreen drawn characters and simulate text input • Key and mouse events are called low-level events because they are close to the hardware interactions the user performs.
  • 3. 3 MouseListener interface public interface MouseListener { public void mouseClicked(MouseEvent event); public void mouseEntered(MouseEvent event); public void mouseExited(MouseEvent event); public void mousePressed(MouseEvent event); public void mouseReleased(MouseEvent event); } • Many AWT/Swing components have this method:  public void addMouseListener(MouseListener ml) • Mouse listeners are often added to custom components and drawing canvases to respond to clicks and other mouse actions.
  • 4. 4 Implementing listener public class MyMouseListener implements MouseListener { public void mouseClicked(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} public void mousePressed(MouseEvent event) { System.out.println("You pressed the button!"); } public void mouseReleased(MouseEvent event) {} } // elsewhere, myComponent.addMouseListener(new MyMouseListener());  Problem: Tedious to implement entire interface when only partial behavior is wanted / needed.
  • 5. 5 Pattern: Adapter an object that fits another object into a given interface
  • 6. 6 Adapter pattern • Problem: We have an object that contains the functionality we need, but not in the way we want to use it.  Cumbersome / unpleasant to use. Prone to bugs. • Example:  We want to write one or two mouse input methods.  Java makes us implement an interface full of methods we don't want. • Solution:  Provide an adapter class that connects into the setup we must talk to (GUI components) but exposes to us the interface we prefer (only have to write one or two methods).
  • 7. 7 Event adapters • event adapter: A class with empty implementations of all of a given listener interface's methods.  examples: MouseAdapter, KeyAdapter, FocusAdapter  Extend MouseAdapter; override methods you want to implement. • Don't have to type in empty methods for the ones you don't want!  an example of the Adapter design pattern  Why is there no ActionAdapter for ActionListener?
  • 8. 8 An abstract event adapter // This class exists in package java.awt.event. // An empty implementation of all MouseListener methods. public abstract class MouseAdapter implements MouseListener { public void mousePressed(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} public void mouseClicked(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} }  Now classes can extend MouseAdapter rather than implementing MouseListener. • client gets the complete mouse listener interface it wants • implementer gets to write just the few mouse methods they want • Why did Sun include MouseListener? Why not just the adapter?
  • 9. 9 Abstract classes • abstract class: A hybrid between an interface and a class.  Defines a superclass type that can contain method declarations (like an interface) and/or method bodies (like a class).  Like interfaces, abstract classes that cannot be instantiated (cannot use new to create any objects of their type). • What goes in an abstract class?  Implementation of common state and behavior that will be inherited by subclasses (parent class role)  Declare generic behavior for subclasses to implement (interface role)
  • 10. 10 Abstract class syntax // declaring an abstract class public abstract class name { ... // declaring an abstract method // (any subclass must implement it) public abstract type name(parameters); } • A class can be abstract even if it has no abstract methods • You can create variables (but not objects) of the abstract type
  • 11. 11 Writing an adapter public class MyMouseAdapter extends MouseAdapter { public void mousePressed(MouseEvent event) { System.out.println("You pressed the button!"); } } // elsewhere, myComponent.addMouseListener(new MyMouseAdapter());
  • 12. 12 Abstract class vs. interface • Why do both interfaces and abstract classes exist in Java?  An abstract class can do everything an interface can do and more.  So why would someone ever use an interface? • Answer: Java has only single inheritance.  can extend only one superclass  can implement many interfaces  Having interfaces allows a class to be part of a hierarchy (polymorphism) without using up its inheritance relationship.
  • 13. 13 MouseEvent properties • MouseEvent  public static int BUTTON1_MASK, BUTTON2_MASK, BUTTON3_MASK, CTRL_MASK, ALT_MASK, SHIFT_MASK  public int getClickCount()  public Point getPoint()  public int getX(), getY()  public Object getSource()  public int getModifiers() // use *_MASK with this • SwingUtilities  static void isLeftMouseButton(MouseEvent event)  static void isRightMouseButton(MouseEvent event)
  • 14. 14 Using MouseEvent public class MyMouseAdapter extends MouseAdapter { public void mousePressed(MouseEvent event) { Object source = event.getSource(); if (source == button && event.getX() < 10) { JOptionPane.showMessageDialog(null, "You clicked the left edge!"); } } }
  • 15. 15 Mouse motion public interface MouseMotionListener { public void mouseDragged(MouseEvent event); public void mouseMoved(MouseEvent event); } • For some reason Java separates mouse input into many interfaces.  The second focuses on the movement of the mouse cursor. • Many AWT/Swing components have this method:  public void addMouseMotionListener( MouseMotionListener ml) • The abstract MouseMotionAdapter class provides empty implementations of both methods if you just want to override one.
  • 16. 16 Mouse wheel scrolling public interface MouseWheelListener { public void mouseWheelMoved(MouseWheelEvent event); }  The third mouse event interface focuses on the rolling of the mouse's scroll wheel button. • Many AWT/Swing components have this method:  public void addMouseWheelListener( MouseWheelListener ml)
  • 17. 17 Mouse input listener // import javax.swing.event.*; public interface MouseInputListener extends MouseListener, MouseMotionListener, MouseWheelListener {} • The MouseInputListener interface combines all kinds of mouse input into a single interface that you can implement. • The MouseInputAdapter class includes empty implementations for all methods from all mouse input interfaces, allowing the same listener object to listen to mouse clicks, movement, and/or wheel events.
  • 18. 18 Mouse input example public class MyMouseInputAdapter extends MouseInputAdapter { public void mousePressed(MouseEvent event) { System.out.println("Mouse was pressed"); } public void mouseDragged(MouseEvent event) { Point p = event.getPoint(); System.out.println("Mouse is at " + p); } } ... // using the listener MyMouseInputAdapter adapter = new MyMouseInputAdapter(); myPanel.addMouseListener(adapter); myPanel.addMouseMotionListener(adapter);
  • 20. 20 KeyListener interface public interface KeyListener { public void keyPressed(KeyEvent event); public void keyReleased(KeyEvent event); public void keyTyped(KeyEvent event); } • Many AWT/Swing components have this method:  public void addKeyListener(KeyListener kl) • The abstract class KeyAdapter implements all KeyListener methods with empty bodies.
  • 21. 21 KeyEvent objects  // what key code was pressed? public static int VK_A, VK_B, ..., VK_Z, VK_0, ... VK_9, VK_F1, ... VK_F10, VK_UP, VK_LEFT, ..., VK_TAB, VK_SPACE, VK_ENTER, ... (one for almost every key)  // Were any modifier keys held down? public static int CTRL_MASK, ALT_MASK, SHIFT_MASK  public char getKeyChar()  public int getKeyCode() // use VK_* with this  public Object getSource()  public int getModifiers() // use *_MASK with this
  • 22. 22 Key event example public class PacManKeyListener extends KeyAdapter { public void keyPressed(KeyEvent event) { char keyChar = event.getKeyChar(); int keyCode = event.getKeyCode(); if (keyCode == KeyEvent.VK_RIGHT) { pacman.setX(pacman.getX() + 1); } else if (keyChar == 'Q') { quit(); } } } // elsewhere, myJFrame.addKeyListener(new PacKeyListener());
  • 24. 24 Focus events public interface FocusListener { public void focusGained(FocusEvent event); public void focusLost(FocusEvent event); } • focus: The current target of keyboard input.  A focus event occurs when the keyboard cursor enters or exits a component, signifying the start/end of typing on that control. • Many AWT/Swing components have this method:  public void addFocusListener(FocusListener kl) • The abstract class FocusAdapter implements all FocusListener methods with empty bodies.
  • 25. 25 Window events public interface WindowListener { public void windowActivated(WindowEvent event); public void windowClosed(WindowEvent event); public void windowClosing(WindowEvent event); public void windowDeactivated(WindowEvent event); public void windowDeiconified(WindowEvent event); public void windowIconified(WindowEvent event); public void windowOpened(WindowEvent event); } • A JFrame object has this method:  public void addWindowListener(WindowListener wl) • The abstract class WindowAdapter implements all WindowListener methods with empty bodies.
  • 26. 26 Change events public interface ChangeListener { public void stateChanged(ChangeEvent event); } • These events occur when some kind of state of a given component changes. Not used by all components, but essential for some. • JSpinner, JSlider, JTabbedPane, JColorChooser, JViewPort, and other components have this method:  public void addChangeListener(ChangeListener cl)
  • 27. 27 Component events public interface ComponentListener { public void componentHidden(ComponentEvent event); public void componentMoved(ComponentEvent event); public void componentResized(ComponentEvent event); public void componentShown(ComponentEvent event); } • These events occur when a layout manager reshapes a component or when it is set to be visible or invisible. • Many AWT/Swing components have this method:  public void addComponentListener(ComponentListener cl) • The abstract class ComponentAdapter implements all ComponentListener methods with empty bodies.
  • 28. 28 JList/JTree select events public interface ListSelectionListener { public void valueChanged(ListSelectionEvent event); } public interface TreeSelectionListener { public void valueChanged(TreeSelectionEvent event); } • These events occur when a user changes the element(s) selected within a JList or JTree. • The JList component has this method:  public void addListSelectionListener( ListSelectionListener lsl) • The JTree component has this method:  public void addTreeSelectionListener( TreeSelectionListener tsl)
  • 29. 29 Document events public interface DocumentListener { public void changedUpdate(DocumentEvent event); public void insertUpdate(DocumentEvent event); public void removeUpdate(DocumentEvent event); } • These events occur when the contents of a text component (e.g. JTextField or JTextArea) change. • Such components have this method:  public Document getDocument() • And a Document object has this method:  public void addDocumentListener(DocumentListener cl) • And yes, there is a DocumentAdapter .