AJP Chapter 1 PPT - Event Handlers and Listeners

23
UID – Event Handling and Listeners

Transcript of AJP Chapter 1 PPT - Event Handlers and Listeners

Page 1: AJP Chapter 1 PPT - Event Handlers and Listeners

UID – Event Handling and Listeners

Page 2: AJP Chapter 1 PPT - Event Handlers and Listeners

Event handling and listeners

• What is an event?user actions and contextevent sources and listeners

• Why should my programs be event- driven?

User interaction with the GUI

Page 3: AJP Chapter 1 PPT - Event Handlers and Listeners

Some typical component events and listeners

Act that results in event ListenerUser clicks a button, presses return while typing in a text field, or chooses a menu item

ActionListener

User closes a window WindowListenerUser presses a mouse button while the cursor is over a component

MouseListener

User moves the mouse over a component MouseMotionListener

Component becomes visible ComponentListenerComponent gets the keyboard focus FocusListenerTable or list selection changes ListSelectionListener

Page 4: AJP Chapter 1 PPT - Event Handlers and Listeners

Implementing listeners (1)

• Three key bits of code1) add interface2) register3) handle

• Components can have multiple listeners

• A simple JButton ActionListener…

Page 5: AJP Chapter 1 PPT - Event Handlers and Listeners

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

Page 6: AJP Chapter 1 PPT - Event Handlers and Listeners

Types of event listeners (1)

• Global component listenersmay be used for any Swing componentsTypes

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)

Page 7: AJP Chapter 1 PPT - Event Handlers and Listeners

Types of event listeners (2)

• Component-specific listenersrelevant to specific components’ actionsTypes

ActionListenerCaretListenerChangeListenerDocumentListenerItemListenerListSelectionListenerWindowListeneretc.

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

Page 8: AJP Chapter 1 PPT - Event Handlers and Listeners

Working with event listeners

• Getting event information

• Low-level events

• Semantic events

• Adapters for event handling

• Inner classes for event handling

Page 9: AJP Chapter 1 PPT - Event Handlers and Listeners

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)

Page 10: AJP Chapter 1 PPT - Event Handlers and Listeners

Low-level and semantic events (1)

• Low-level events - window-system levele.g. mouse, key, component, container, focus, windowtrigger component-independent

• Semantic eventseverything else! – e.g. action, item, list selectiontrigger can differ by component

e.g. button click and textfield ‘return’ action events

Page 11: AJP Chapter 1 PPT - Event Handlers and Listeners

Low-level and semantic events (2)

• Listen for semantic events whenever possible

Gives robust and portable codeeg Button - listen for action event rather than mouse event. Means that button responds to keyboard shortcuts.

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

Page 12: AJP Chapter 1 PPT - Event Handlers and Listeners

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 codeSay you only want mouseClicked to do something then all others have to be implemented but empty

• Alternative….

Page 13: AJP Chapter 1 PPT - Event Handlers and Listeners

Adapters for event handling (2)

• ... is to extend a MouseAdapter classinherits 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...}

}

Page 14: AJP Chapter 1 PPT - Event Handlers and Listeners

Inner classes for event handling (1)

• Don’t want to / cant inherit from an adapter class?

there’s no multiple inheritance in Javaeg 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

Page 15: AJP Chapter 1 PPT - Event Handlers and Listeners

Inner classes for event handling (2)

• Anonymous classes -used to simplify codegood 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

}});...

}

Page 16: AJP Chapter 1 PPT - Event Handlers and Listeners

Threads and Swing (1)

• Why use them?Improved perceived performanceCan remove time consuming task from event thread to keep GUI responsiveInitialisation of program so GUI appears faster

• Potential problemsDeadlock the application if access any realised swing components from non event threads.

Page 17: AJP Chapter 1 PPT - Event Handlers and Listeners

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

}

Page 18: AJP Chapter 1 PPT - Event Handlers and Listeners

Threads and Swing (3)

• invokeLater()requests that event thread runs certain codecan be called from any threadcode goes in run method of Runable objectreturns immediately without waiting for event thread to execute code.

Runnable updateAComponent = new Runnable() {public void run() {component.doSomething(); }};SwingUtilities.invokeLater(updateAComponent);

Page 19: AJP Chapter 1 PPT - Event Handlers and Listeners

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);}

Page 20: AJP Chapter 1 PPT - Event Handlers and Listeners

Summary - but not the end...

• Implementing event listeners• Types of event listeners• Handling event listeners

getting event informationlow-level and semantic eventsadaptersinner classes - named and anonymous

• Threads

Page 21: AJP Chapter 1 PPT - Event Handlers and Listeners

What Covered So Far?

• What is Swing?• Containers

FramesDialogs(applets)

• ComponentsLoads to choose from

• Layout Managers‘Educated Trial and Error’

• Events and User Interaction

Page 22: AJP Chapter 1 PPT - Event Handlers and Listeners

A simple Swing program

• Uses components in containers• Lays components out correctly• Listens for events

• An example:SwingExample.java (revisited)…Code on Course Website…

Page 23: AJP Chapter 1 PPT - Event Handlers and Listeners

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