A JButton listener example

JButton listener FAQ: A common Java JButton question is "How do I add a listener to a JButton?", or the equivalent, "How can I tell when a JButton is pressed?"

JButton listener solution

In short, you typically want to add an ActionListener to a JButton, as shown in the following source code snipet:

JButton showDialogButton = new JButton("Text Button");
showDialogButton.addActionListener(new ActionListener()
{
  public void actionPerformed(ActionEvent e)
  {
    // display/center the jdialog when the button is pressed
    JDialog d = new JDialog(frame, "Hello", true);
    d.setLocationRelativeTo(frame);
    d.setVisible(true);
  }
});

You then put the code you want to run when the button is pressed in the actionPerformed method of the ActionListener. There are several ways to actually implement this, including the following:

  • Implement it as shown above
  • Have your class implement an ActionListener
  • Create a separate class as an ActionListener, i.e., in this example naming it something like DisplayJButtonActionListener

There are other ways to do this, but those are common approaches. As a warning, in a large application you're definitely going to want an organized approach.

A complete JButton listener example

I usually like to provide complete source code examples, and to that end, here's a complete Java class that shows this JButton listener/pressed approach:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JButtonListenerExample
{
  static JFrame frame;

  public static void main(String[] args)
  {
    // schedule this for the event dispatch thread (edt)
    SwingUtilities.invokeLater(new Runnable()
    {
      public void run()
      {
        displayJFrame();
      }
    });
  }

  static void displayJFrame()
  {
    frame = new JFrame("Our JButton listener example");

    // create our jbutton
    JButton showDialogButton = new JButton("Click Me");
    
    // add the listener to the jbutton to handle the "pressed" event
    showDialogButton.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        // display/center the jdialog when the button is pressed
        JDialog d = new JDialog(frame, "Hello", true);
        d.setLocationRelativeTo(frame);
        d.setVisible(true);
      }
    });

    // put the button on the frame
    frame.getContentPane().setLayout(new FlowLayout());
    frame.add(showDialogButton);

    // set up the jframe, then display it
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setPreferredSize(new Dimension(300, 200));
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}

I hope all of this JButton listener/pressed example code is helpful.

More JButton and ActionListener information

For more information on the JButton and ActionListener classes, check out these Javadoc pages: