24
Event Handling and Event Handling and Listeners in SWING Listeners in SWING The practice of event The practice of event handling handling

Event Handling and Listeners in SWING The practice of event handling

Embed Size (px)

DESCRIPTION

Implementing listeners Three key bits of code Three key bits of code 1) add interface1) add interface 2) register2) register 3) handle3) handle Components can have multiple listeners Components can have multiple listeners A simple JButton ActionListener … A simple JButton ActionListener … To write an Action Listener, follow the steps given below: 1.Declare an event handler class and specify that the class either implements an ActionListener interface or extends a class that implements an ActionListener interface. For example: public class MyClass implements ActionListener { 2.Register an instance of the event handler class as a listener on one or more components. For example: someComponent.addActionListener(instanceOfMyClass); 3.Include code that implements the methods in listener interface. For example: public void actionPerformed(ActionEvent e) {...//code that reacts to the action... }

Citation preview

Page 1: Event Handling and Listeners in SWING The practice of event handling

Event Handling and Event Handling and Listeners in SWINGListeners in SWING

The practice of event The practice of event handlinghandling

Page 2: Event Handling and Listeners in SWING The practice of event handling

Some swing component Some swing component events and listenersevents and listeners

Act that results in event Act that results in event ListenerListenerUser clicks a button, presses User clicks a button, presses rreturn while typing eturn while typing in a text field, or chooses a menu itemin a text field, or chooses a menu item

ActionListenerActionListener

User closes a User closes a windowwindow WindowListenerWindowListener User presses a mouse button while the cursor is User presses a mouse button while the cursor is over a component over a component

MouseListenerMouseListener

User moves the mouse over a component User moves the mouse over a component MouseMotionListenMouseMotionListenerer

Component becomes visible Component becomes visible ComponentListeneComponentListenerr

Component gets the keyboard focus Component gets the keyboard focus FocusListenerFocusListener Table or list selection changes Table or list selection changes ListSelectionListenListSelectionListen

erer

Page 3: Event Handling and Listeners in SWING The practice of event handling

Implementing listenersImplementing listeners Three key bits of codeThree key bits of code

• 1) add interface1) add interface• 2) register2) register• 3) handle3) handle

Components can have multiple listenersComponents can have multiple listeners

A simple JButton ActionListenerA simple JButton ActionListener……

To write an Action Listener, follow the steps given below:

1. Declare an event handler class and specify that the class either implements an ActionListener interface or extends a class that implements an ActionListener interface.

For example: public class MyClass implements ActionListener {

2. Register an instance of the event handler class as a listener on one or more components.

For example: someComponent.addActionListener(instanceOfMyClass);

3. Include code that implements the methods in listener interface.

For example: public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... }

Page 4: Event Handling and Listeners in SWING The practice of event handling

Implementing listeners (2)Implementing listeners (2)

public class myClass … implements public class myClass … implements ActionListenerActionListener { { ……

// where setting up occurs (e.g. constructor)// where setting up occurs (e.g. constructor)JButton button = new JButton(“I am a button”);JButton button = new JButton(“I am a button”);button.button.addActionListeneraddActionListener(this);(this); ……public void public void actionPerformed(ActionEvent e)actionPerformed(ActionEvent e) { {…… // respond to event// respond to event

} // end response method } // end response method } // end class} // end class

Page 5: Event Handling and Listeners in SWING The practice of event handling

Implementing listeners (2)Implementing listeners (2)import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;

public class AL extends Frame implements WindowListener,ActionListener {public class AL extends Frame implements WindowListener,ActionListener {TextField text = new TextField(20);TextField text = new TextField(20);Button b;Button b;private int numClicks = 0;private int numClicks = 0;

public static void main(String[] args) {public static void main(String[] args) {AL myWindow = new AL("My first window");AL myWindow = new AL("My first window");myWindow.setSize(350,100);myWindow.setSize(350,100);myWindow.setVisible(true);myWindow.setVisible(true);}}

public AL(String title) {public AL(String title) {

super(title);super(title);setLayout(new FlowLayout());setLayout(new FlowLayout());addWindowListener(this);addWindowListener(this);b = new Button("Click me");b = new Button("Click me");add(b);add(b);add(text);add(text);b.addActionListener(this);b.addActionListener(this);}}

public void actionPerformed(ActionEvent e) {public void actionPerformed(ActionEvent e) {numClicks++;numClicks++;text.setText("Button Clicked " + numClicks + " times");text.setText("Button Clicked " + numClicks + " times");}}

public void windowClosing(WindowEvent e) {public void windowClosing(WindowEvent e) {dispose();dispose();System.exit(0);System.exit(0);}}

public void windowOpened(WindowEvent e) {}public void windowOpened(WindowEvent e) {}public void windowActivated(WindowEvent e) {}public void windowActivated(WindowEvent e) {}public void windowIconified(WindowEvent e) {}public void windowIconified(WindowEvent e) {}public void windowDeiconified(WindowEvent e) {}public void windowDeiconified(WindowEvent e) {}public void windowDeactivated(WindowEvent e) {}public void windowDeactivated(WindowEvent e) {}public void windowClosed(WindowEvent e) {}public void windowClosed(WindowEvent e) {}

Set up things:

public class AL extends Frame implements windowListener,ActionListener { TextField text = new TextField(20); Button b; private int numClicks = 0;

Page 6: Event Handling and Listeners in SWING The practice of event handling

Implementing listeners (2)Implementing listeners (2)import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;

public class AL extends Frame implements WindowListener,ActionListener {public class AL extends Frame implements WindowListener,ActionListener {TextField text = new TextField(20);TextField text = new TextField(20);Button b;Button b;private int numClicks = 0;private int numClicks = 0;

public static void main(String[] args) {public static void main(String[] args) {AL myWindow = new AL("My first window");AL myWindow = new AL("My first window");myWindow.setSize(350,100);myWindow.setSize(350,100);myWindow.setVisible(true);myWindow.setVisible(true);}}

public AL(String title) {public AL(String title) {

super(title);super(title);setLayout(new FlowLayout());setLayout(new FlowLayout());addWindowListener(this);addWindowListener(this);b = new Button("Click me");b = new Button("Click me");add(b);add(b);add(text);add(text);b.addActionListener(this);b.addActionListener(this);}}

public void actionPerformed(ActionEvent e) {public void actionPerformed(ActionEvent e) {numClicks++;numClicks++;text.setText("Button Clicked " + numClicks + " times");text.setText("Button Clicked " + numClicks + " times");}}

public void windowClosing(WindowEvent e) {public void windowClosing(WindowEvent e) {dispose();dispose();System.exit(0);System.exit(0);}}

public void windowOpened(WindowEvent e) {}public void windowOpened(WindowEvent e) {}public void windowActivated(WindowEvent e) {}public void windowActivated(WindowEvent e) {}public void windowIconified(WindowEvent e) {}public void windowIconified(WindowEvent e) {}public void windowDeiconified(WindowEvent e) {}public void windowDeiconified(WindowEvent e) {}public void windowDeactivated(WindowEvent e) {}public void windowDeactivated(WindowEvent e) {}public void windowClosed(WindowEvent e) {}public void windowClosed(WindowEvent e) {}

We would like to handle the button-click event, so we add an action listener to the button b as below: b = new Button("Click me"); b.addActionListener(this);

Page 7: Event Handling and Listeners in SWING The practice of event handling

Implementing listeners (2)Implementing listeners (2)import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;

public class AL extends Frame implements WindowListener,ActionListener {public class AL extends Frame implements WindowListener,ActionListener {TextField text = new TextField(20);TextField text = new TextField(20);Button b;Button b;private int numClicks = 0;private int numClicks = 0;

public static void main(String[] args) {public static void main(String[] args) {AL myWindow = new AL("My first window");AL myWindow = new AL("My first window");myWindow.setSize(350,100);myWindow.setSize(350,100);myWindow.setVisible(true);myWindow.setVisible(true);}}

public AL(String title) {public AL(String title) {

super(title);super(title);setLayout(new FlowLayout());setLayout(new FlowLayout());addWindowListener(this);addWindowListener(this);b = new Button("Click me");b = new Button("Click me");add(b);add(b);add(text);add(text);b.addActionListener(this);b.addActionListener(this);}}

public void actionPerformed(ActionEvent e) {public void actionPerformed(ActionEvent e) {numClicks++;numClicks++;text.setText("Button Clicked " + numClicks + " times");text.setText("Button Clicked " + numClicks + " times");}}

public void windowClosing(WindowEvent e) {public void windowClosing(WindowEvent e) {dispose();dispose();System.exit(0);System.exit(0);}}

public void windowOpened(WindowEvent e) {}public void windowOpened(WindowEvent e) {}public void windowActivated(WindowEvent e) {}public void windowActivated(WindowEvent e) {}public void windowIconified(WindowEvent e) {}public void windowIconified(WindowEvent e) {}public void windowDeiconified(WindowEvent e) {}public void windowDeiconified(WindowEvent e) {}public void windowDeactivated(WindowEvent e) {}public void windowDeactivated(WindowEvent e) {}public void windowClosed(WindowEvent e) {}public void windowClosed(WindowEvent e) {}

public void actionPerformed(ActionEvent e) {numClicks++;text.setText("Button Clicked " + numClicks + " times");

Now, when the user clicks the Button b, the button fires an action event which invokes the action listener's actionPerformed method.

Page 8: Event Handling and Listeners in SWING The practice of event handling

Types of event listeners Types of event listeners Global component listenersGlobal component listeners

• may be used for any Swing componentsmay be used for any Swing components

Types of global listenersTypes of global listeners ComponentListener (changes in size, position, visibility)ComponentListener (changes in size, position, visibility) FocusListener (whether ability for keyboard input)FocusListener (whether ability for keyboard input) KeyListener (key press events, only with focus)KeyListener (key press events, only with focus) MouseListener (clicks and movement into/out of MouseListener (clicks and movement into/out of

component area)component area) MouseMotionListener (changes in position over MouseMotionListener (changes in position over

component)component)

Page 9: Event Handling and Listeners in SWING The practice of event handling

Types of event listeners (2)Types of event listeners (2)

Component-specific listenersComponent-specific listeners• relevant to specific components’ actionsrelevant to specific components’ actions• TypesTypes

ActionListenerActionListener CaretListener CaretListener ChangeListenerChangeListener DocumentListenerDocumentListener ItemListenerItemListener ListSelectionListenerListSelectionListener WindowListenerWindowListener etc.etc.

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

Page 10: Event Handling and Listeners in SWING The practice of event handling

Working with event listenersWorking with event listeners

Getting event informationGetting event information

Low-level eventsLow-level events

Semantic eventsSemantic events

Adapters for event handlingAdapters for event handling

Inner classes for event handlingInner classes for event handling

Page 11: Event Handling and Listeners in SWING The practice of event handling

Getting event informationGetting event information EventObjectEventObject class - use sub classes of this to class - use sub classes of this to

determine what’s happened.determine what’s happened. Get the firing object with Get the firing object with getSource()getSource();; Actual event classes sometimes have specific typesActual event classes sometimes have specific types

• e.g. the e.g. the ComponentListenerComponentListener uses a sub-class of uses a sub-class of EventObjectEventObject : : ComponentEventComponentEvent that has that has getComponentgetComponent();();

Event classes may define methods that return Event classes may define methods that return more informationmore information• e.g. e.g. ActionEventActionEvent has a method for getting modifiers has a method for getting modifiers

(Shift, Alt, Ctrl)(Shift, Alt, Ctrl)

Page 12: Event Handling and Listeners in SWING The practice of event handling

Low-level and semantic eventsLow-level and semantic events

Low-level eventsLow-level events - window-system level - window-system level• e.g. mouse, key, component, container, focus, e.g. mouse, key, component, container, focus,

windowwindow• trigger component-independenttrigger component-independent

Semantic eventsSemantic events• everything else! – e.g. action, item, list selectioneverything else! – e.g. action, item, list selection• trigger can differ by componenttrigger can differ by component

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

Page 13: Event Handling and Listeners in SWING The practice of event handling

Low-level and semantic events Low-level and semantic events

Listen for semantic events whenever possible Listen for semantic events whenever possible

• Gives robust and portable codeGives robust and portable code eg Button - listen for action event rather than mouse eg Button - listen for action event rather than mouse

event. Means that button responds to keyboard event. Means that button responds to keyboard shortcuts.shortcuts.

• Compound componentsCompound components eg combo box - no real way of guaranteeing low level eg combo box - no real way of guaranteeing low level

listeners on all look and feel specific components used listeners on all look and feel specific components used to form the compound component.to form the compound component.

Page 14: Event Handling and Listeners in SWING The practice of event handling

Adapters for event handlingAdapters for event handling Classes which implement listener interfaces Classes which implement listener interfaces

must implement all listener methodsmust implement all listener methods• e.g. e.g. MouseListenerMouseListener has 5 methods: has 5 methods: mouseClickedmouseClicked, , mouseReleasedmouseReleased, , mousePressedmousePressed, , mouseEnteredmouseEntered, , mouseExitedmouseExited

This leads to cluttered codeThis leads to cluttered code• Say you only want Say you only want mouseClickedmouseClicked to do to do

something then all others have to be something then all others have to be implemented but emptyimplemented but empty

Alternative….Alternative….

Page 15: Event Handling and Listeners in SWING The practice of event handling

Adapters for event handling (2)Adapters for event handling (2) ... is to extend a MouseAdapter class... is to extend a MouseAdapter class

• inherits empty definitions of all five inherits empty definitions of all five mouseListener methods. Eg:mouseListener methods. Eg:

public class MyClass extends MouseAdapter {public class MyClass extends MouseAdapter {... ...

someObject.addMouseListener(this); someObject.addMouseListener(this); ... ... public void mouseClicked(MouseEvent e) { public void mouseClicked(MouseEvent e) {

//Event handler implementation goes //Event handler implementation goes here...here...

} } }}

Page 16: Event Handling and Listeners in SWING The practice of event handling

Inner classes for event handling Inner classes for event handling Don’t want to / cant inherit from an adapter Don’t want to / cant inherit from an adapter

class?class?• there’s no multiple inheritance in Javathere’s no multiple inheritance in Java

eg can’t extend JPanel AND MouseAdaptereg can’t extend JPanel AND MouseAdapter• Solution: use an inner classSolution: use an inner class

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

} // end MyClass} // end MyClass

Page 17: Event Handling and Listeners in SWING The practice of event handling

Inner classes for event handling Inner classes for event handling (2)(2)

Anonymous classes - Anonymous classes - • used to simplify codeused to simplify code• good when only 1 instance will ever be neededgood when only 1 instance will ever be needed

public class MyClass extends JPanel { public class MyClass extends JPanel { ... ... someObject.addMouseListener(new MouseAdapter() { someObject.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) { public void mouseClicked(MouseEvent e) { //Event handler implementation goes here//Event handler implementation goes here

}} });}); ... ...

} }

Page 18: Event Handling and Listeners in SWING The practice of event handling

Threads and Swing Threads and Swing

Why use them?Why use them?• Improved perceived performanceImproved perceived performance• Can remove time consuming task from event Can remove time consuming task from event

thread to keep GUI responsivethread to keep GUI responsive• Initialisation of program so GUI appears fasterInitialisation of program so GUI appears faster

Potential problemsPotential problems• Deadlock the application if access any realised Deadlock the application if access any realised

swing components from non event threads.swing components from non event threads.

Page 19: Event Handling and Listeners in SWING The practice of event handling

Threads and SwingThreads and Swing Remember the rule:Remember the rule:

• Once a Swing component has been realised, all code that might Once a Swing component has been realised, all code that might affect or depend on the state of that component should be affect or depend on the state of that component should be executed in the event-dispatching thread.executed in the event-dispatching thread.

If code does not need to be in event thread then:If code does not need to be in event thread then:public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {

final SwingWorker worker = new SwingWorker() { final SwingWorker worker = new SwingWorker() { public Object construct() { public Object construct() { //---code that might take a while to execute is here...//---code that might take a while to execute is here... return return someValuesomeValue; ; }}

}; }; worker.start(); //required for SwingWorker 3worker.start(); //required for SwingWorker 3

}}

Page 20: Event Handling and Listeners in SWING The practice of event handling

Threads and Swing Threads and Swing

invokeLater()invokeLater()• requests that event thread runs certain coderequests that event thread runs certain code• can be called from any threadcan be called from any thread• code goes in run method of Runable objectcode goes in run method of Runable object• returns immediately without waiting for returns immediately without waiting for

event thread to execute code.event thread to execute code.

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

};};SwingUtilities.invokeLater(updateAComponent);SwingUtilities.invokeLater(updateAComponent);

Page 21: Event Handling and Listeners in SWING The practice of event handling

Threads and Swing (4)Threads and Swing (4)

invokeAndWait()invokeAndWait()• identical to identical to invokeLater()invokeLater() except doesn’t return except doesn’t return

till event thread has finished executing the code.till event thread has finished executing the code.• Should use this if possible - less chance of Should use this if possible - less chance of

deadlock.deadlock.

void showHelloThereDialog() throws Exception {void showHelloThereDialog() throws Exception { Runnable showModalDialog = new Runnable() {Runnable showModalDialog = new Runnable() { public void run() {public void run() { JOptionPane.showMessageDialog(myMainFrame,JOptionPane.showMessageDialog(myMainFrame, "Hello There");"Hello There"); }} };}; SwingUtilities.invokeAndWait(showModalDialog);SwingUtilities.invokeAndWait(showModalDialog);

}}

Page 22: Event Handling and Listeners in SWING The practice of event handling

Summary Summary Implementing event listenersImplementing event listeners Types of event listenersTypes of event listeners Handling event listenersHandling event listeners

• getting event informationgetting event information• low-level and semantic eventslow-level and semantic events• adaptersadapters• inner classes - named and anonymousinner classes - named and anonymous

ThreadsThreads

Page 23: Event Handling and Listeners in SWING The practice of event handling

A simple Swing programA simple Swing program Uses components in containersUses components in containers Lays components out correctlyLays components out correctly Listens for eventsListens for events

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

Page 24: Event Handling and Listeners in SWING The practice of event handling

A (Slightly) More Complex A (Slightly) More Complex Swing programSwing program

Uses components in containers (again)Uses components in containers (again)

Lays components out correctly (again - but Lays components out correctly (again - but more complex)more complex)

Listens for events - Multiple listenersListens for events - Multiple listeners

Another example: Another example: • SwingExample2.javaSwingExample2.java