Events and Event Listeners in Java

Updated August 2021 for Swing


Here is how Java processes events:

We'll go over these in detail below

I. Low-level Events

Low-level events represent a low-level input or window operation, like a key press, mouse movement, or window opening. The following table displays the different low-level events, and the operations that generate each event (each operation corresponds to a method of the listener interface):

Event Type Description of what causes the event ID from e.getId() Useful Methods (on the event object)
ComponentEvent Hiding, moving, resizing, showing COMPONENT_MOVED ?
COMPONENT_RESIZED
COMPONENT_SHOWN
COMPONENT_HIDDEN
ContainerEvent Adding / removing component   ?
FocusEvent Getting / losing focus FOCUS_GAINED e.getOppositeComponent() will tell you which component lost/gained focus in this focus change
Use component.requestFocus() to get the focus,
You might need component.setFocusable(true) as well.
FOCUS_LOST
KeyEvent Pressing, releasing, or typing (both) a key KEY_PRESSED e.getKeyCode()
// Keyboard code for the pressed key.
int key = e.getKeyCode(); 
if (key == KeyEvent.VK_LEFT) { 
// left-arrow key;
KEY_RELEASED
KEY_TYPED
MouseEvent Clicking, dragging, entering, exiting, moving, pressing, or releasing MOUSE_CLICKED e.getX() : int x-coordinate
e.getY() : int x-coordinate

e.isShiftDown()
boolean: is the shift key down
e.isAltDown()
e.isControlDown()
e.isMetaDown() : for the AppleKey on the Mac
MOUSE_DRAGGED
MOUSE_ENTERED
MOUSE_EXITED
MOUSE_MOVED
MOUSE_PRESSED
MOUSE_RELEASED
WindowEvent Iconifying, deiconifying, opening, closing, really closed, activating, deactivating WINDOW_CLOSED ?
WINDOW_CLOSING
WINDOW_DEICONIFIED
WINDOW_ICONIFIED
WINDOW_OPENED

For instance, typing the letter 'A' on the keyboard generates three events, one for pressing, one for releasing, and one for typing. Depending upon your interests, you can do something for any of the three events.

II. Semantic Events

Semantic events represent interaction with a GUI component; for instance selecting a button, or changing the text of a text field. Which components generate which events is shown in the next section.The semantic events are generated by the following

Obsolete AWT events new Swing Events
 
Event Type ID from e.getId() Object Action Useful Methods (on the event object)
ActionEvent ACTION_PERFORMED JButton Click on Button e.getActionCommand() - returns the value of the "action command" associated with the button (or menu item) that was set with setActionCommand()
If no setActionCommand, it returns the text on the button.
e.getActionCommand()
- returns text from TextField
e.getModifiers()
e.getSource()
: can be used for any event
e.g. Object target = e.getSource(); 
// which component produced this event? if (target instanceof Button) System.out.print("Button was clicked.");
  JList Double-click on an item
  JMenuItem Click on MenuItem
  JTextField Press <Enter> key
  javax.Swing.Timer ★ The ActionEvent is fired every n milliseconds A Swing Timer should have a separate ActionListener class from other ActionEvents to minimize confusion.
AdjustmentEvent ADJUST_VALUE_CHANGED Scrollbar Any Scrollbar action e.getValue() : returns the value that the scrollbar is set to
ChangeEvent
?
JSlider
JSpinner
JColorChooser 
Any JSlider action e.getValue() : returns the value that the scrollbar is set to
ItemEvent ITEM_STATE_CHANGED Choice (?)
JComboBox
Select an item

e.getItem().toString() : returns "name" of object
e.getStateChange() : tells whether it is being selected or deselected
( ItemEvent.SELECTED or ItemEvent.DESELECTED )

e.g.   if (e.getStateChange() == ItemEvent.SELECTED) {
  JList Select or deselect an item
  JCheckbox
JRadioButton
Select or deselect an item
TextEvent TEXT_VALUE_CHANGED TextArea
TextField
Text changed ?
DocumentEvent
?
JTextArea
JTextField
Text changed ?

Event Sources and Listeners (this tells you which listener to use for which event)

The following table show the different event sources.

Summary of Listener interfaces and their methods

Event Source
Event Type Listener Interface Adapter Class Interface Methods
(all are required)
JButton
JList
JMenuItem
JTextField
ActionEvent ActionListener none actionPerformed ()
Timer ★
ActionEvent ActionListener none actionPerformed ()
Scrollbar
 AdjustmentEvent  AdjustmentListener none adjustmentValueChanged ()
JSlider
JSpinner
JColorChooser
 ChangeEvent  ChangeListener none stateChanged ()
all Components
ComponentEvent ComponentListener ComponentAdapter componentHidden ()
componentMoved ()
componentResized ()
componentShown
()
Container
ContainerEvent ContainerListener ContainerAdapter componentAdded ()
componentRemoved
()
all Component
FocusEvent FocusListener FocusAdapter focusGained ()
focusLost
()
Choice
JComboBox
JCheckbox
JRadioButton
List
ItemEvent ItemListener none itemStateChanged ()
all Components
KeyEvent KeyListener KeyAdapter keyPressed ()
keyReleased ()
keyTyped
()
all Components
MouseEvent MouseListener MouseAdapter mouseClicked ()
mouseEntered ()
mouseExited ()
mousePressed ()
mouseReleased
()
all Components
MouseEvent MouseMotionListener MouseMotionAdapter mouseDragged ()
mouseMoved
()
TextArea
TextField
TextEvent TextListener none textValueChanged ()
JTextArea, JTextField DocumentEvent DocumentListener none changedUpdate ()
insertUpdate ()
removeUpdate ()
Window,
JDialog, JOptionPane,
JFrame
WindowEvent WindowListener
WindowStateListener
WindowFocusListener
WindowAdapter windowActivated ()
windowClosed ()
windowClosing ()
windowDeactivated ()
windowDeiconified ()
windowIconified ()
windowOpened()
windowStateChanged()
windowGainedFocus()
windowLostFocus()

Event Adapters

Since the low-level event listeners have multiple methods to implement, there are event adapter classes to ease the pain. Instead of implementing the interface and stubbing out the methods you do not care about, you can subclass the appropriate adapter class and just override the one or two methods you are interested in. If listeners only contain one method to implement, there is no need for adapter classes.

Event Listeners
+ can be used if extending other classes
- you need to add ALL methods even if you don't use them

public class MyKeystroke extends ABCDE implements KeyListener {
@Override public void keyPressed(KeyEvent e) { System.out.println("User typed: " + KeyEvent.getKeyText(e.getKeyCode())); } @Override public void keyReleased(KeyEvent e) {} //required, but does nothing //NOTE: keyPressed() reacts much faster than keyTyped() so use it @Override public void keyTyped(KeyEvent e) {} //required, but does nothing }

 

Event Adapters
+ you only need one method
- you cannot extend any other superclass

public class MyKeyAdapter extends KeyAdapter {		//same as above, but with a KeyAdapter instead

  @Override
  public void keyTyped(KeyEvent e) {
    System.out.println("User typed: " +
      KeyEvent.getKeyText(e.getKeyCode()));
  }
}

Events Generated by Swing Components

Table: http://docs.oracle.com/javase/tutorial/uiswing/events/eventsandcomponents.html
and https://docs.oracle.com/javase/tutorial/uiswing/events/api.html


Note that can you remove Event Listeners as well.


Old stuff:

When you have a very common operation,it often makes sense to abstract out this behavior and handle it elsewhere - by subclassing. For example handling application window closing events (a poor example) we can extend JFrame class to AppFrame and then all of your JFrames just use this. This avoids having to put all of this code into each class.
  public void windowClosing(WindowEvent e) {
    setVisible(false);
    dispose();
    System.exit(0);
  }
  public void windowClosed(WindowEvent e) {}
  public void windowDeactivated(WindowEvent e) {}
  public void windowActivated(WindowEvent e) {}
  public void windowDeiconified(WindowEvent e) {}
  public void windowIconified(WindowEvent e) {}
  public void windowOpened(WindowEvent e) {}
}