Handling GUI Generated Events 2

GUI Behavior:-

This section describes the event categories.

Event Categories:-

  • The general mechanism for receiving events from components has been described in the context of a single type of event.
  • Many of the event classes reside in the java.awt.event package, but other exist in the API.
  • For each category of events, an interface has to be implemented by the class objects that want to receive the events.
  • That interface demands that one or more methods be defined as well. Those methods are called when particular events arise.
  • The given below lists these categories and interfaces:

Category              Interface Name             Methods

Action                   ActionListener               actionPerformed(ActionEvent)

Item                     ItemListener                            itemStateChanged(ItemEvent)

Mouse                   MouseListener               mousePressed(MouseEvent)





MouseMotion       MouseMotionListener    mouseDragged(MouseEvent)


Key                      KeyListener                             keyPressed(KeyEvent)



Focus                             FocusListener                focusGained(FocusEvent)


Adjustment          AdjustmentListener       adjustmentValueChanged(                                                                                   AdjustmentEvent)

Component          ComponentListener       componentMoved(ComponentEvent)




Window               WindowListener            windowClosing(WindowEvent)







Container             ContainerListener          componentAdded(ContainerEvent)


Window state       WindowStateListener    windowStateChanged(WindowEvent)

Window focus      WindowFocusListener   windowGainedFocus(WindowEvent)


Hierarchy             HierarchyListener          hierarchyChanged(HierarchyEvent)

AWT                    AWTEventListener        eventDispatched(AWTEvent)

Text                      TextListener                            textValueChanged(TextEvent)

Complex Example:-

  • This section examines a more complex Java code software example. It tracks the movement of the mouse when the mouse button is pressed (mouse dragging).
  • It also detects mouse movement even when the buttons are not pressed (mouse moving).
  • The events caused by moving the mouse with or without a button pressed can be picked up by objects of a class that implements the MouseMotionListener interface.
  • This interface requires two methods, mouseDragged() and mouseMoved().
  • Even if you are interested only in the drag movement, you must provide both methods. However, the body of the mouseMoved() method can be empty.
  • To pick up other mouse events, including mouse clicking, you must implement the MouseListener interface.
  • This interface does include several events, including mouseEntered, mouseExited, mousePressed, mouseReleased, and mouseClicked.
  • When mouse or keyboard events occur, information about the position of the mouse or the key that was pressed is available in the event that it generated.
  • In the code given below, events are handled within the class named TwoListener.


Handling GUI Generated Events


  1. import javax.swing.*;
  2. import java.awt.event;
  3. import java.awt.*;
  4. public class TwoListener implements MouseMotionListener, MouseListener
  5. {
  6. private JFrame f;
  7. private JTextField tf;
  8. public TwoListener()
  9. {
  10. f = new JFrame(“Two listeners example”);
  11. tf = new JTextField(30);
  12. }
  13. public void launchFrame()
  14. {
  15. JLabel label = new JLabel(“Click and drag the mouse”);
  16. // add components to the frame
  17. f.add(label, BorderLayout.NORTH);
  18. f.add(label, BorderLayout.SOUTH);
  19. // add this object as a listener
  20. f.addMouseMotionListener(this);
  21. f.addMouseListener(this);
  22. // size the frame and make it visible
  23. f.setSize(300, 200);
  24. f.setVisible(true);
  25. }
  26. // these are MouseMotionListener events
  27. public void mouseDragged(MouseEvent e)
  28. {
  29. String s = “Mouse dragging: X = ” + e.getX() + “Y = ” + e.getY();
  30. tf.setText(s);
  31. }
  32. public void mouseEntered(MouseEvent e)
  33. {
  34. String s = “The mouse entered”;;
  35. tf.setText(s);
  36. }
  37. public void mouseExited(MouseEvent e)
  38. {
  39. String s = “The mouse has left the building”;
  40. tf.setText(s);
  41. }
  42. // unused MouseMotionListener method.
  43. // all methods of a listener must be present in the class if they are not used.
  44. public void mouseMoved(MouseEvent e)
  45. {
  46. // unused MouseListener method.
  47. public void mousePressed(MouseEvent e){ }
  48. public void mouseClicked(MouseEvent e){ }
  49. public void mouseReleased(MouseEvent e){ }
  50. public static void main(String[] args)
  51. {
  52. TwoListener two = new TwoListener();
  53. two.launchFrame();
  54. }
  55. }
  56. }

Implementing Multiple Interfaces:-

The class is declared in Line 5 using the following:

implements MouseMotionListener, MouseListener

You can declare multiple interfaces by using comma separation.

Listening to Multiple Sources:-

  • If you issue the following method calls in lines 24 and 25.



  • Both types of events cause methods to be called in the TwoListener class. An object can listen to as many event sources as required. The objects class needs to implement only the required interfaces.

Obtaining Details about the Event:-

  • The event arguments with which handler methods, such as mouseDragged(), are called contain potentially important information about the original event.
  • To determine the details of what information is available for each category of event, check the appropriate class documentation in the java.awt.event package.

Multiple Listeners:-

  • The AWT event listening framework permits the attachment of multiple listeners to the same component.
  • In general, if you choose to write a program that performs multiple actions based on a single event, include code for that behavior in your handler method.
  • However, sometimes a program’s design requires multiple, unrelated parts of the same program to react to the same event.
  • This might happen if, for example, a context sensitive help system is added to an existing program.
  • The listener mechanism enables you to call an addXxxListener() method as many times as needed, and you can specify as many different listeners as your design requires.
  • All registered listeners have their handler methods called when the event occur.

Note: – The order in which the handler methods are called is undefined. Generally, if the order of invocation matters, then thehandlers are not unrelated. In this case, register only the first listener and have that listener call others directly.

Sourabh Bhunje

Sourabh Bhunje, B.E. IT from Pune University. Currently Working at Techliebe. Professional Skills: Programming - Software & Mobile, Web & Graphic Design, Localization, Content Writing, Sub-Titling etc. http://techliebe.com/about-us

Leave a Reply