How do I handle a button click in Java Swing?

Use addActionListener() to run code when a JButton is activated. In this example, clicking a button changes the text of a label in the same window.

Source code

Save the following code as ButtonClickExample.java:

import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class ButtonClickExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        JLabel message = new JLabel(
                "Click the button.", SwingConstants.CENTER);
        JButton button = new JButton("Click me");

        button.addActionListener(event ->
                message.setText("Button clicked!"));

        JPanel panel = new JPanel(new BorderLayout(0, 12));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 30, 20, 30));
        panel.add(message, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(button);
        panel.add(buttonPanel, BorderLayout.PAGE_END);

        JFrame frame = new JFrame("Button Click");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Illustration showing the label before and after clicking the Swing button

Explanation

The JLabel starts with the text Click the button.. The JButton displays Click me. This line connects the button to the label:

button.addActionListener(event ->
        message.setText("Button clicked!"));

addActionListener() registers a listener that Swing calls when the button is activated. The lambda is the listener in this example. Its event parameter receives information about the action, but the example only needs to update the label, so it does not use that parameter.

When the listener runs, message.setText() changes the existing label. It works whether you click the button with a mouse or activate it with the keyboard.

SwingUtilities.invokeLater() creates the window on the event dispatch thread. Swing also runs the listener on that thread, so it can update the label directly. Keep listeners short so the window stays responsive.

Run the example

javac ButtonClickExample.java
java ButtonClickExample

The window opens with the message Click the button.. Click Click me and the label changes to Button clicked!.

How do I customize JButton icons?

The example below shows you how we can customize the icon for JButton Swing components.

package org.kodejava.swing;

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

public class JButtonCustomIcon extends JFrame {
    public JButtonCustomIcon() throws HeadlessException {
        initialize();
    }

    private void initialize() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        JButton button = new JButton("Press Me!");

        // Below is how we can set various icons for the JButton swing
        // component. There are the default icon, selected, disabled, pressed
        // and rollover icons.
        button.setIcon(new ImageIcon("default.png"));
        button.setSelectedIcon(new ImageIcon("selected.png"));
        button.setDisabledIcon(new ImageIcon("disabled.png"));
        button.setDisabledSelectedIcon(new ImageIcon("disabledSelected.png"));
        button.setPressedIcon(new ImageIcon("pressed.png"));
        button.setRolloverIcon(new ImageIcon("rollover.png"));
        button.setRolloverSelectedIcon(new ImageIcon("rolloverSelected.png"));

        getContentPane().add(button);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new JButtonCustomIcon().setVisible(true));
    }
}

How do I display an image in JButton?

package org.kodejava.swing;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.FlowLayout;

public class ButtonImageExample extends JFrame {
    public ButtonImageExample() {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new ButtonImageExample().setVisible(true));
    }

    private void initComponents() {
        setTitle("My Buttons");
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));

        // Creates two JButton object with an images to display. The image can be
        // a gif, jpeg, png and some other type supported. And we also set the
        // mnemonic character of the button for short-cut key.
        JButton okButton = new JButton("OK", new ImageIcon(
                this.getClass().getResource("/images/ok.png")));
        okButton.setMnemonic('O');
        JButton cancelButton = new JButton("Cancel", new ImageIcon(
                this.getClass().getResource("/images/cancel.png")));
        cancelButton.setMnemonic('C');

        getContentPane().add(okButton);
        getContentPane().add(cancelButton);
    }
}
JButton with Image Icon
JButton with Image Icon