Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Event Handling and Listeners in SWING The practice of event handling."— Presentation transcript:

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

2 Some swing component events and listeners Act that results in event Listener User clicks a button, presses return while typing in a text field, or chooses a menu item ActionListener User closes a 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 Component gets the keyboard focus FocusListener Table or list selection changes ListSelectionListener

3 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... }

4 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

5 Implementing listeners (2) import java.awt.*; import java.awt.event.*; public class AL extends Frame implements WindowListener,ActionListener { TextField text = new TextField(20); Button b; private int numClicks = 0; public static void main(String[] args) { AL myWindow = new AL("My first window"); myWindow.setSize(350,100);myWindow.setVisible(true);} public AL(String title) { super(title); setLayout(new FlowLayout()); addWindowListener(this); b = new Button("Click me"); add(b);add(text);b.addActionListener(this);} public void actionPerformed(ActionEvent e) { numClicks++; text.setText("Button Clicked " + numClicks + " times"); } public void windowClosing(WindowEvent e) { dispose();System.exit(0);} public void windowOpened(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowDeactivated(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;

6 Implementing listeners (2) import java.awt.*; import java.awt.event.*; public class AL extends Frame implements WindowListener,ActionListener { TextField text = new TextField(20); Button b; private int numClicks = 0; public static void main(String[] args) { AL myWindow = new AL("My first window"); myWindow.setSize(350,100);myWindow.setVisible(true);} public AL(String title) { super(title); setLayout(new FlowLayout()); addWindowListener(this); b = new Button("Click me"); add(b);add(text);b.addActionListener(this);} public void actionPerformed(ActionEvent e) { numClicks++; text.setText("Button Clicked " + numClicks + " times"); } public void windowClosing(WindowEvent e) { dispose();System.exit(0);} public void windowOpened(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowDeactivated(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);

7 Implementing listeners (2) import java.awt.*; import java.awt.event.*; public class AL extends Frame implements WindowListener,ActionListener { TextField text = new TextField(20); Button b; private int numClicks = 0; public static void main(String[] args) { AL myWindow = new AL("My first window"); myWindow.setSize(350,100);myWindow.setVisible(true);} public AL(String title) { super(title); setLayout(new FlowLayout()); addWindowListener(this); b = new Button("Click me"); add(b);add(text);b.addActionListener(this);} public void actionPerformed(ActionEvent e) { numClicks++; text.setText("Button Clicked " + numClicks + " times"); } public void windowClosing(WindowEvent e) { dispose();System.exit(0);} public void windowOpened(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowDeactivated(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.

8 Types of event listeners Global component listeners Global component listeners may be used for any Swing componentsmay be used for any Swing components Types of global listeners Types 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 component area) MouseListener (clicks and movement into/out of component area) MouseMotionListener (changes in position over component) MouseMotionListener (changes in position over component)

9 Types of event listeners (2) Component-specific listeners Component-specific listeners relevant to specific components’ actionsrelevant to specific components’ actions TypesTypes ActionListener ActionListener CaretListener CaretListener ChangeListener ChangeListener DocumentListener DocumentListener ItemListener ItemListener ListSelectionListener ListSelectionListener WindowListener WindowListener etc. etc. See: See: http://java.sun.com/docs/books/tutorial/uiswing/events/eventsandcomp onents.html http://java.sun.com/docs/books/tutorial/uiswing/events/eventsandcomp onents.html

10 Working with event listeners Getting event information Getting event information Low-level events Low-level events Semantic events Semantic events Adapters for event handling Adapters for event handling Inner classes for event handling Inner classes for event handling

11 Getting event information EventObject class - use sub classes of this to determine what’s happened. EventObject class - use sub classes of this to determine what’s happened. EventObject Get the firing object with getSource(); Get the firing object with getSource(); getSource Actual event classes sometimes have specific types Actual event classes sometimes have specific types e.g. the ComponentListener uses a sub-class of EventObject : ComponentEvent that has getComponent();e.g. the ComponentListener uses a sub-class of EventObject : ComponentEvent that has getComponent(); ComponentListener getComponent ComponentListener getComponent Event classes may define methods that return more information Event classes may define methods that return more information e.g. ActionEvent has a method for getting modifiers (Shift, Alt, Ctrl)e.g. ActionEvent has a method for getting modifiers (Shift, Alt, Ctrl)

12 Low-level and semantic events Low-level events - window-system level Low-level events - window-system level e.g. mouse, key, component, container, focus, windowe.g. mouse, key, component, container, focus, window trigger component-independenttrigger component-independent Semantic events Semantic 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 events e.g. button click and textfield ‘return’ action events

13 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 event. Means that button responds to keyboard shortcuts. eg Button - listen for action event rather than mouse event. Means that button responds to keyboard shortcuts. Compound componentsCompound 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. eg combo box - no real way of guaranteeing low level listeners on all look and feel specific components used to form the compound component.

14 Adapters for event handling Classes which implement listener interfaces must implement all listener methods Classes which implement listener interfaces must implement all listener methods e.g. MouseListener has 5 methods: mouseClicked, mouseReleased, mousePressed, mouseEntered, mouseExitede.g. MouseListener has 5 methods: mouseClicked, mouseReleased, mousePressed, mouseEntered, mouseExited This leads to cluttered code This leads to cluttered code Say you only want mouseClicked to do something then all others have to be implemented but emptySay you only want mouseClicked to do something then all others have to be implemented but empty Alternative…. Alternative….

15 AdaptersAdapters for event handling (2) Adapters... is to extend a MouseAdapter class... is to extend a MouseAdapter class inherits empty definitions of all five mouseListener methods. Eg: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... }}

16 Inner classes Inner classes for event handling Inner classes Don’t want to / cant inherit from an adapter class? Don’t want to / cant inherit from an adapter class? there’s no multiple inheritance in Javathere’s no multiple inheritance in Java eg can’t extend JPanel AND MouseAdapter eg 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()); … class myAdapter extends MouseAdapter { public void mouseClicked(MouseEvent e) { public void mouseClicked(MouseEvent e) { // blah } // end mouseClicked } // end mouseClicked } // end inner class } // end MyClass

17 Inner classes for event handling (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() { public void mouseClicked(MouseEvent e) { //Event handler implementation goes here } }); });......}

18 ThreadsThreads and Swing Threads Why use them? Why use them? Improved perceived performanceImproved perceived performance Can remove time consuming task from event thread to keep GUI responsiveCan remove time consuming task from event thread to keep GUI responsive Initialisation of program so GUI appears fasterInitialisation of program so GUI appears faster Potential problems Potential problems Deadlock the application if access any realised swing components from non event threads.Deadlock the application if access any realised swing components from non event threads.

19 Threads and Swing Remember the rule: 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.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: 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... //---code that might take a while to execute is here... return someValue; return someValue;} }; }; worker.start(); //required for SwingWorker 3 }

20 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 event thread to execute code.returns immediately without waiting for event thread to execute code. Runnable updateAComponent = new Runnable() { public void run() {component.doSomething(); } public void run() {component.doSomething(); }};SwingUtilities.invokeLater(updateAComponent);

21 Threads and Swing (4) invokeAndWait() invokeAndWait() identical to invokeLater() except doesn’t return till event thread has finished executing the code.identical to invokeLater() except doesn’t return till event thread has finished executing the code. Should use this if possible - less chance of deadlock.Should use this if possible - less chance of deadlock. 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);}

22 Summary Implementing event listeners Implementing event listeners Types of event listeners Types of event listeners Handling event listeners Handling 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 Threads Threads

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

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


Download ppt "Event Handling and Listeners in SWING The practice of event handling."

Similar presentations


Ads by Google