JButton and Action Listeners - potatoscript/JavaSwing GitHub Wiki

🎮 JButton and Action Listeners in Java Swing 🖱️

🎯 What is JButton?

JButton is a button that performs an action when clicked. It is one of the most commonly used Swing components for capturing user input.

Key Features:

  • 🎨 Customizable Text & Icon: Set text and icon on the button.
  • Handles User Actions: Can detect mouse clicks and perform an action.
  • 🖼️ Supports Styles & Borders: Customize button appearance easily.

📚 Step 1: Creating a Basic JButton


📝 Basic Syntax

import javax.swing.*;

public class MyButton {
    public static void main(String[] args) {
        // Create JFrame
        JFrame frame = new JFrame("JButton Example");

        // Create JButton
        JButton button = new JButton("Click Me!");

        // Add button to frame
        frame.add(button);

        // Set frame properties
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

🎨 Explanation

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

  • Creates a button with the label "Click Me!".

frame.add(button);

  • Adds the button to the frame.

frame.setSize(300, 200);

  • Sets the window size to 300x200 pixels.

frame.setVisible(true);

  • Displays the window.

👩‍🎨 Output:

+---------------------+
|     Click Me!        |
+---------------------+

🎨 Step 2: Adding Action Listener to JButton


🎯 What is an Action Listener?

An Action Listener is used to detect button clicks and perform an action in response. It listens for ActionEvent and executes code when the button is clicked.


📝 Basic Example with Action Listener

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

public class ButtonWithAction {
    public static void main(String[] args) {
        // Create JFrame
        JFrame frame = new JFrame("Button with ActionListener");

        // Create JButton
        JButton button = new JButton("Click Me!");

        // Add Action Listener
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(frame, "🎉 Button Clicked!");
            }
        });

        // Add button to frame
        frame.add(button);

        // Set frame properties
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

🎨 Explanation

button.addActionListener(new ActionListener() { ... });

  • Adds an ActionListener to the button.

public void actionPerformed(ActionEvent e)

  • Defines the action to perform when the button is clicked.

JOptionPane.showMessageDialog(frame, "🎉 Button Clicked!");

  • Displays a popup message when the button is clicked.

👩‍🎨 Output:

+---------------------+
|     Click Me!        |
+---------------------+

➡️ Click the button:

+-------------------+
| 🎉 Button Clicked! |
+-------------------+

🎨 Step 3: Using Lambda Expression for Action Listener


Simplify Action Listener using Lambda Expression (Java 8+)

import javax.swing.*;

public class ButtonWithLambda {
    public static void main(String[] args) {
        // Create JFrame
        JFrame frame = new JFrame("Button with Lambda");

        // Create JButton
        JButton button = new JButton("Click Me!");

        // Add Action Listener using Lambda
        button.addActionListener(e -> JOptionPane.showMessageDialog(frame, "🎉 Button Clicked with Lambda!"));

        // Add button to frame
        frame.add(button);

        // Set frame properties
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

🎨 Explanation

button.addActionListener(e -> { ... });

  • Lambda expression to handle button click events.

JOptionPane.showMessageDialog(frame, "...");

  • Displays a message box when the button is clicked.

👩‍🎨 Output:

+---------------------+
|     Click Me!        |
+---------------------+

➡️ Click the button:

+--------------------------+
| 🎉 Button Clicked with Lambda! |
+--------------------------+

📚 Step 4: JButton with Multiple Actions


📝 Example: Multiple Buttons with Different Actions

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

public class MultipleButtons {
    public static void main(String[] args) {
        // Create JFrame
        JFrame frame = new JFrame("Multiple Buttons Example");

        // Create JPanel to hold buttons
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());

        // Create Buttons
        JButton button1 = new JButton("Say Hello");
        JButton button2 = new JButton("Show Time");
        JButton button3 = new JButton("Exit");

        // Add Action Listeners
        button1.addActionListener(e -> JOptionPane.showMessageDialog(frame, "👋 Hello!"));
        button2.addActionListener(e -> JOptionPane.showMessageDialog(frame, "⏰ Current Time: " + java.time.LocalTime.now()));
        button3.addActionListener(e -> System.exit(0));

        // Add buttons to panel
        panel.add(button1);
        panel.add(button2);
        panel.add(button3);

        // Add panel to frame
        frame.add(panel);

        // Set frame properties
        frame.setSize(400, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

🎨 Explanation

button1.addActionListener(e -> { ... });

  • Displays "👋 Hello!" message.

button2.addActionListener(e -> { ... });

  • Displays the current time using LocalTime.now().

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

  • Exits the application when clicked.

👩‍🎨 Output:

+-------------------------------+
| [Say Hello] [Show Time] [Exit] |
+-------------------------------+

➡️ Click Say Hello:

+---------------+
| 👋 Hello!      |
+---------------+

➡️ Click Show Time:

+--------------------------+
| ⏰ Current Time: 12:34 PM |
+--------------------------+

➡️ Click Exit:

  • Closes the application.

🎨 Step 5: JButton with Icon and Tooltip


📝 Adding Icons to JButton

import javax.swing.*;

public class ButtonWithIcon {
    public static void main(String[] args) {
        // Create JFrame
        JFrame frame = new JFrame("Button with Icon");

        // Create Icon
        ImageIcon icon = new ImageIcon("icon.png");

        // Create JButton with Icon
        JButton button = new JButton("Click Me!", icon);

        // Add Tooltip
        button.setToolTipText("This is a button with an icon.");

        // Add button to frame
        frame.add(button);

        // Set frame properties
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

🎨 Explanation

ImageIcon icon = new ImageIcon("icon.png");

  • Loads an image from icon.png file.

new JButton("Click Me!", icon);

  • Creates a button with text and an icon.

button.setToolTipText("...");

  • Adds a tooltip that displays when hovering over the button.

👩‍🎨 Output:

+----------------------+
| [Icon] Click Me!      |
+----------------------+

📚 Step 6: JButton Methods and Properties


Method Description Example Code
setText(String text) Sets the button text. button.setText("New Text");
getText() Gets the button text. String text = button.getText();
setIcon(Icon icon) Sets an icon on the button. button.setIcon(new ImageIcon("icon.png"));
setEnabled(boolean enabled) Enables/disables the button. button.setEnabled(false);
setToolTipText(String text) Sets a tooltip text when hovering. button.setToolTipText("Info here");
setBackground(Color color) Sets the background color. button.setBackground(Color.BLUE);
setForeground(Color color) Sets the text color. button.setForeground(Color.WHITE);
setMnemonic(char key) Assigns a keyboard shortcut. button.setMnemonic('C');
setBorder(Border border) Sets a border around the button. button.setBorder(BorderFactory.createLineBorder(Color.BLACK));
doClick() Simulates a button click programmatically. button.doClick();

🎁 Bonus: Simulating Button Clicks

// Simulate button click
button.doClick();