UID Event Handling and. Listener. Event handling and listeners. Some typical component events and listeners. Boriana Koleva

UID – Event Handling and Listeners Boriana Koleva ([email protected]) Event handling and listeners • What is an event? Š user actions and context Š e...
Author: Henry Parks
3 downloads 2 Views 149KB Size
UID – Event Handling and Listeners Boriana Koleva ([email protected])

Event handling and listeners • What is an event? Š user actions and context Š event sources and listeners

• Why should my programs be eventdriven? Š User interaction with the GUI

Some typical component events and listeners Act that results in event

Listener

User clicks a button, presses return while typing ActionListener in a text field, or chooses a menu item WindowListener User closes a window User presses a mouse button while the cursor is MouseListener over a component User moves the mouse over a component

MouseMotionListener

Component becomes visible

ComponentListener

Component gets the keyboard focus

FocusListener

Table or list selection changes

ListSelectionListener

1

Implementing listeners (1) • Three key bits of code Š 1) add interface Š 2) register Š 3) handle

• Components can have multiple listeners

• A simple JButton ActionListener…

Implementing listeners (2) public class myClass … implements ActionListener { … // where setting up occurs (e.g. constructor) JButton button = new JButton(“I am a button”); button.addActionListener(this); … public void actionPerformed(ActionEvent e) { … // respond to event } // end response method } // end class

Types of event listeners (1) • Global component listeners Š may be used for any Swing components Š Types ƒ ƒ ƒ ƒ

ComponentListener (changes in size, position, visibility) FocusListener (whether ability for keyboard input) KeyListener (key press events, only with focus) MouseListener (clicks and movement into/out of component area) ƒ MouseMotionListener (changes in position over component)

2

Types of event listeners (2) • Component-specific listeners Š relevant to specific components’ actions Š Types ƒ ƒ ƒ ƒ ƒ ƒ ƒ ƒ

ActionListener CaretListener ChangeListener DocumentListener ItemListener ListSelectionListener WindowListener etc.

• See: http://java.sun.com/docs/books/tutorial/uiswing/events/eventsandcomponents.html

Working with event listeners

• Getting event information • Low-level events • Semantic events • Adapters for event handling • Inner classes for event handling

Getting event information • EventObject class - use sub classes of this to determine what’s happened. • Get the firing object with getSource(); • Actual event classes sometimes have specific types Š e.g. the ComponentListener uses a sub-class of EventObject : ComponentEvent that has getComponent();

• Event classes may define methods that return more information Š e.g. ActionEvent has a method for getting modifiers (Shift, Alt, Ctrl)

3

Low-level and semantic events (1) • Low-level events - window-system level Š e.g. mouse, key, component, container, focus, window Š trigger component-independent

• Semantic events Š everything else! – e.g. action, item, list selection Š trigger can differ by component ƒ e.g. button click and textfield ‘return’ action events

Low-level and semantic events (2) • Listen for semantic events whenever possible Š Gives robust and portable code ƒ eg Button - listen for action event rather than mouse event. Means that button responds to keyboard shortcuts.

Š Compound components ƒ eg combo box - no real way of guaranteeing low level listeners on all look and feel specific components used to form the compound component.

Adapters for event handling (1) • Classes which implement listener interfaces must implement all listener methods Š e.g. MouseListener has 5 methods: mouseClicked, mouseReleased, mousePressed, mouseEntered, mouseExited

• This leads to cluttered code Š Say you only want mouseClicked to do something then all others have to be implemented but empty

• Alternative….

4

Adapters for event handling (2) • ... is to extend a MouseAdapter class Š inherits empty definitions of all five mouseListener methods. Eg: public class MyClass extends MouseAdapter { ... someObject.addMouseListener(this); ... public void mouseClicked(MouseEvent e) { //Event handler implementation goes here... } }

Inner classes for event handling (1) • Don’t want to / cant inherit from an adapter class? Š there’s no multiple inheritance in Java ƒ eg can’t extend JPanel AND MouseAdapter

Š Solution: use an inner class • public class MyClass extends JPanel { … anObject.addMouseListener(new myAdapter()); … class myAdapter extends MouseAdapter { public void mouseClicked(MouseEvent e) { // blah } // end mouseClicked } // end inner class } // end MyClass

Inner classes for event handling (2) • Anonymous classes Š used to simplify code Š good when only 1 instance will ever be needed •

public class MyClass extends JPanel { ... someObject.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { //Event handler implementation goes here } }); ... }

5

Threads and Swing (1) • Why use them? Š Improved perceived performance Š Can remove time consuming task from event thread to keep GUI responsive Š Initialisation of program so GUI appears faster

• Potential problems Š Deadlock the application if access any realised swing components from non event threads.

Threads and Swing (2) • Remember the rule: Š Once a Swing component has been realised, all code that might affect or depend on the state of that component should be executed in the event-dispatching thread.

• If code does not need to be in event thread then: public void actionPerformed(ActionEvent e) { final SwingWorker worker = new SwingWorker() { public Object construct() { //---code that might take a while to execute is here... return someValue; } }; worker.start(); //required for SwingWorker 3 }

Threads and Swing (3) • invokeLater() Š requests that event thread runs certain code Š can be called from any thread Š code goes in run method of Runable object Š returns immediately without waiting for event thread to execute code. Runnable updateAComponent = new Runnable() { public void run() {component.doSomething(); } }; SwingUtilities.invokeLater(updateAComponent);

6

Threads and Swing (4) • invokeAndWait() Š identical to invokeLater() except doesn’t return till event thread has finished executing the code. Š Should use this if possible - less chance of deadlock. void showHelloThereDialog() throws Exception { Runnable showModalDialog = new Runnable() { public void run() { JOptionPane.showMessageDialog(myMainFrame, "Hello There"); } }; SwingUtilities.invokeAndWait(showModalDialog); }

Summary - but not the end... • Implementing event listeners • Types of event listeners • Handling event listeners Š getting event information Š low-level and semantic events Š adapters Š inner classes - named and anonymous

• Threads

What Covered So Far? • What is Swing? • Containers Š Frames Š Dialogs Š (applets)

• Components Š Loads to choose from

• Layout Managers Š ‘Educated Trial and Error’

• Events and User Interaction

7

A simple Swing program • Uses components in containers • Lays components out correctly • Listens for events • An example: Š SwingExample.java (revisited)… Š Code on Course Website…

A (Slightly) More Complex Swing program • Uses components in containers (again) • Lays components out correctly (again - but more complex) • Listens for events - Multiple listeners • Another example: Š SwingExample2.java

8

Suggest Documents