Java Swing Tutorial - Event








An event in Swing is an action taken by a user. For example, pressing a button, pressing a key down/up on the keyboard.

The source of an event is the component that generates the event. For example, when we press a JButton, the clicked event occurs on that JButton. In this case, the JButton is the source of the clicked event.

An event represents the action that takes place on the source component.

Action Event

The ActionListener interface has one method called actionPerformed(). The interface declaration is as follows:

public interface  ActionListener extends EventListener {
    void  actionPerformed(ActionEvent event);
}

All event listener interfaces inherit from the java.util.EventListener interface.

The EventListener interface is a marker interface, and it does not have any methods.

When a JButton is pressed, the actionPerformed() method of all its registered Action listeners is called.

The following code uses a lambda expression to add an Action listener to a JButton:

closeButton.addActionListener(e ->  System.exit(0));

The following code shows how to add click event handler for the close button to exit a Swing application.

import java.awt.Container;
//from  w w  w. ja v a 2  s  .c o  m
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("JFrame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    // Add a close button
    JButton closeButton = new JButton("Close");
    contentPane.add(closeButton);

    closeButton.addActionListener(e -> System.exit(0));
    
    frame.pack();
    frame.setVisible(true);
  }
}




Example

The following code adds action listener to a button with anonymous class.

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*from  ww  w  .j  ava  2  s.co  m*/
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
  static int counter;

  public static void main(String[] args) {

    JFrame frame = new JFrame("JFrame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    JButton counterButton = new JButton("Clicked #0");
    JButton closeButton = new JButton("Close");
    frame.setLayout(new FlowLayout());
    contentPane.add(closeButton);
    contentPane.add(counterButton);

    counterButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        counterButton.setText("Clicked #" + counter++);
      }
    });

    closeButton.addActionListener(e -> System.exit(0));

    frame.pack();
    frame.setVisible(true);
  }
}




Example 2

This example shows how to get the action command from a JButton. The action command is a string object and we can use it to figure which button is clicked.

import java.awt.Container;
/*from   w  w  w  .  j a va 2 s . c  o m*/
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("JFrame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    // Add a close button
    JButton closeButton = new JButton("Close");
    contentPane.add(closeButton);

    closeButton.addActionListener(e ->{
      System.out.println(e.getActionCommand());
      System.exit(0);
    } );
    
    frame.pack();
    frame.setVisible(true);
  }
}

Mouse Events

We can handle mouse events such as mouse click, enter, exit, press, and release on a component.

An object of the MouseEvent class represents a Mouse event on a component.

To handle Mouse events, use the MouseListener interface. Here is how the interface is declared:

public interface MouseListener extends EventListener {
  public void mouseClicked(MouseEvent e);

  public void mousePressed(MouseEvent e);

  public void mouseReleased(MouseEvent e);

  public void mouseEntered(MouseEvent e);

  public void mouseExited(MouseEvent e);
}

The MouseListener interface has five methods and we cannot use a lambda expression to create mouse event handler.

One of the methods of the MouseListener interface is called when a specific mouse event occurs.

The MouseEvent class has methods to give us the details about a mouse event:

The getClickCount() method returns the number of clicks a mouse made. The getX() and getY() methods return the x and y positions of the mouse. The getXOnScreen() and getYOnScreen() methods return the absolute x and y positions of the mouse.

The following code demonstrates the mouse entered and exited event for a JButton.

import java.awt.Container;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
//from  w  w  w.ja  v  a  2  s .co m
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("JFrame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    JButton closeButton = new JButton("Close");
    contentPane.add(closeButton);

    closeButton.addActionListener(e -> System.exit(0));
    // Add a MouseListener to the JButton
    closeButton.addMouseListener(new MouseListener() {
      @Override
      public void mouseClicked(MouseEvent e) {
      }

      @Override
      public void mousePressed(MouseEvent e) {
      }

      @Override
      public void mouseReleased(MouseEvent e) {
      }

      @Override
      public void mouseEntered(MouseEvent e) {
        closeButton.setText("Mouse has  entered!");
      }

      @Override
      public void mouseExited(MouseEvent e) {
        closeButton.setText("Mouse has  exited!");
      }
    });
    frame.pack();
    frame.setVisible(true);
  }
}

Event Adapter

Swing includes a convenience class for some Event Listener interfaces. The class is named ending with Adapter.

An Adapter class is declared abstract and it implements one kind of Listener interface.

The Adapter class provides empty implementation for all methods in the Event Listener interface.

Not all event listener interfaces have corresponding adapter classes. The event listener interface with more than one method has a corresponding adapter class.

The following code rewrites the event handler in the code above.

import java.awt.Container;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/*from  w  ww  .  j ava 2 s  .c om*/
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("JFrame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    JButton closeButton = new JButton("Close");
    contentPane.add(closeButton);

    closeButton.addActionListener(e -> System.exit(0));
    // Add a MouseListener to the JButton
    closeButton.addMouseListener(new  MouseAdapter() {
      @Override
      public void  mouseEntered(MouseEvent e)  {
        closeButton.setText("Mouse has  entered!");
      }

      @Override
      public void  mouseExited(MouseEvent e)  {
        closeButton.setText("Mouse has  exited!");
      }
      });
    frame.pack();
    frame.setVisible(true);
  }
}