– To detect when the user clicks an onscreen button (or does the keyboard equivalent), a program must have an object that implements the ActionListener interface. – The program must r[r]
Trang 1CÔNG NGHỆ JAVA
CH10 Handling Mouse and Keyboard Events - SWING components
Giảng viên: Lê Nhật Tùng www.lenhattung.com
Trang 2Topics in This Section
Basic of Event Handling
General asynchronous event-handling strategy
Event-handling options
Handling events with separate listeners
Handling events by implementing interfaces
Handling events with named inner classes
Handling events with anonymous inner classes
The standard AWT listener types
Subtleties with mouse events
Trang 3Basic of Event Handling
Every time the user types a character or pushes a mouse button, an event occurs
• Events : Objects that describe what happened
• Event sources : The generator of an event
• Event handlers : A method that receives an event object, deciphers it, and processes the user’s interaction.
Trang 4Delegation Model of Event
An event can be sent to many event handlers Event handlers register with components when they are interested in events generated by that
component.
Trang 5A Listener Example
public class TestButton {
JFrame frame;
JButton button;
public TestButton() {
frame = new JFrame("Test");
button = new JButton("Press Me!");
button.setActionCommand("ButtonPressed");
// register event listener for button
button.addActionListener(new ButtonHandler());
frame.add(button, BorderLayout.CENTER );
}
public void launchFrame() {
frame.pack();
frame.setVisible(true);
Trang 6A Listener Example (Contd.)
class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Action occurred");
System.out.println("Button’s command is: " +
e.getActionCommand());
}
}
Trang 7Event Categories
Class Hierarchy of GUI Events:
Trang 8Listener Type
Some Events and Their Associated Event
Listeners:
Act that Results in the Event Listener 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 component MouseMotionListener Component becomes visible ComponentListener
Trang 9• ActionListener Interface:
–Has only one method: actionPerformed(ActionEvent)
–To detect when the user clicks an onscreen button (or does the keyboard equivalent), a program must have an object
that implements the ActionListener interface.
–The program must register this object as an action listener
on the button (the event source), using the
addActionListener() method.
–When the user clicks the onscreen button, the button fires
an action event.
Trang 10Listeners (Contd.)
To detect the mouse clicking, a program must have an object that implements the
MouseListener interface.
This interface includes several events including
mouseEntered , mouseExited , mousePressed ,
mouseReleased , and mouseClicked
When the user clicks the onscreen button, the button fires an action event.
Trang 11Listeners (Contd.)
Implementing Multiple Interfaces:
A class can be declared with Multiple Interfaces
by using comma separation:
implements MouseListener, MouseMotionListener
Listening to Multiple Sources:
Multiple listeners cause unrelated parts of a
program to react to the same event.
The handlers of all registered listeners are
called when the event occurs.
Trang 12General Strategy
Determine what type of listener is of interest
11 standard AWT listener types.
ActionListener, ItemListener, KeyListener, MouseListener, MouseMotionListener, TextListener, AdjustmentListener, ComponentListener,
ContainerListener, FocusListener, WindowListener
Define a class of that type
Implement interface (KeyListener, MouseListener, …) Extend class (KeyAdapter, MouseAdapter, etc.)
Register an object of your listener class with the
component
comp.addXxxListener(new MyListenerClass());
E.g., addKeyListener, addMouseListener
Trang 13Case 1 - Using Separate
Listener Classes
Trang 14Separate Listener: Simple Case
Listener does not need to call any methods
of the window to which it is attached
public class MouseClickFrame extends JFrame {
public MouseClickFrame(String title) {
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
addMouseListener(new ClickListener());
setSize(300, 400);
setVisible(true);
}
public static void main(String[] args) {
new MouseClickFrame("Mouse Click");
}
Trang 15Separate Listener: Simple Case
class ClickListener extends MouseAdapter {
private int radius = 25;
public void mousePressed(MouseEvent event) {
JFrame comp = (JFrame) event.getSource();
Graphics g = comp.getGraphics();
g.fillOval(event.getX() - radius,
event.getY() - radius,
2 * radius, 2 * radius);
}
}
Trang 16Separate Listener: Simple Case (Cont')
• Register an object of ClickListener for frame
• Define a class ClickListener extends
MouseAdapter class and override mousePress()
method.
• General event Handling :
–Call event.getSource() to obtain a reference to
window or GUI component from which event originated
–Cast result to type of interest
–Call methods on that reference
•get a Graphics object of component (frame) and draw
Trang 17MouseListener and MouseAdapter
public interface MouseListener {
public void mouseClicked(MouseEvent e);
public void mousePressed(MouseEvent e);
public void mouseReleased(MouseEvent e);
public void mouseEntered(MouseEvent e);
public void mouseExited(MouseEvent e);
}
public abstract class MouseAdapter implements MouseListener {
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
Trang 18Implementing a Listener Interface
class ClickListener implements MouseListener {
private int radius = 25;
public void mousePressed(MouseEvent event) {
JFrame app = (JFrame) event.getSource();
Graphics g = app.getGraphics();
g.fillOval(event.getX() - radius,
event.getY() - radius,
2 * radius, 2 * radius);
}
public void mouseClicked(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) {}
}
Trang 19Implementing a Listener Interface
public class MouseClickFrame extends JFrame {
public MouseClickFrame(String title) {
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
addMouseListener(new ClickListener());
setSize(300, 400);
setVisible(true);
}
public static void main(String[] args) {
new MouseClickFrame("Mouse Click");
}
}
Trang 20Adapters vs Interfaces: Method Signature Errors
• What if you goof on the method signature?
– public void mousepressed(MouseEvent e)
– public void mousePressed()
• Interfaces
–Compile time error
• Adapters
– No compile time error, but nothing happens at run time
when you press the mouse
• Solution for adapters: @Override annotation
–Whenever you think you are overriding a method, put
@Override on the line above the start of the method.
– If that method is not actually overriding an inherited