Adding a JButton to an Application Window in Java Swing

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

public class SwingButtonDemo {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Swing Button Demo");
            frame.setBounds(100, 100, 450, 300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().setLayout(null);

            JButton b1 = new JButton("Close window");
            b1.setBounds(171, 92, 130, 30);
            b1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Close button clicked! Exiting application...");
                    System.exit(0);
                }
            });
            frame.getContentPane().add(b1);
            frame.setVisible(true);

             // Programmatic click demonstration:
            b1.doClick();
        });
    }
}

Terminal Output:

Close button clicked! Exiting application...
[GUI Window Rendered: 450x300, JButton b1="Close window" at (171, 92, 130, 30)]

1. Setting Up Absolute Layout in WindowBuilder 🔝

To place buttons precisely using coordinates (see setBounds() Tutorial), first assign Absolute Layout to your content pane in Eclipse WindowBuilder:

2. Adding JButton and Editing Properties 🔝

Under the components palette, click JButton and drop it onto your window. Use the Properties pane to change the variable name (e.g. b1) and button text:

Swing button Properties in Eclipse

3. Modern Java 8+ Lambda Expressions for Click Events 🔝

While WindowBuilder generates anonymous inner classes by default, Java 8+ allows concise lambda expressions:

import javax.swing.*;

public class ModernLambdaClickDemo {
    public static void main(String[] args) {
        JButton b1 = new JButton("Submit Form");
        JLabel status = new JLabel("Pending");
         // Modern Java 8+ lambda replaces verbose anonymous ActionListener:
        b1.addActionListener(e -> {
            status.setText("Submitted at " + System.currentTimeMillis());
            System.out.println("Lambda action triggered: " + e.getActionCommand());
        });
        b1.doClick();
    }
}

Terminal Output:

Lambda action triggered: Submit Form

4. Safe Window Closing: System.exit(0) vs frame.dispose() 🔝

In WindowBuilder, double-clicking a button inserts the action event handler. In simple standalone programs, System.exit(0); closes the window and terminates the JVM process:

Swing button close event

In multi-window applications (see Data Transfer between Windows), use frame.dispose() instead of System.exit(0) so you only close the child window without killing the parent application:

import javax.swing.*;

public class SafeWindowCloseDemo {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Child Window");
        JButton b1 = new JButton("Close Child");
        b1.addActionListener(e -> {
             // Closes this window without terminating the entire JVM:
            frame.dispose();
            System.out.println("Child window disposed cleanly.");
        });
        b1.doClick();
    }
}

Terminal Output:

Child window disposed cleanly.

5. Dynamically Enabling and Disabling a Button 🔝

To prevent duplicate form submissions or indicate that required fields are missing, toggle setEnabled():

import javax.swing.JButton;

public class EnableDisableButtonDemo {
    public static void main(String[] args) {
        JButton b1 = new JButton("Process Order");
        System.out.println("Initial button enabled state: " + b1.isEnabled());

        b1.setEnabled(false);  // Disables button and greys out text
        System.out.println("After b1.setEnabled(false): " + b1.isEnabled());

        b1.setEnabled(true);   // Re-enables button
        System.out.println("After b1.setEnabled(true): " + b1.isEnabled());
    }
}

Terminal Output:

Initial button enabled state: true
After b1.setEnabled(false): false
After b1.setEnabled(true): true

6. Adding Helpful Tooltips and Keyboard Mnemonic Shortcuts 🔝

Enhance usability by adding hover tooltips and keyboard shortcuts with setToolTipText() and setMnemonic():

import java.awt.event.KeyEvent;
import javax.swing.JButton;

public class TooltipMnemonicDemo {
    public static void main(String[] args) {
        JButton b1 = new JButton("Save (Alt+S)");
        b1.setToolTipText("Click to save student changes to database");
        b1.setMnemonic(KeyEvent.VK_S);  // Keyboard shortcut Alt+S
        System.out.println("Mnemonic key code: " + b1.getMnemonic() + ", Tooltip: " + b1.getToolTipText());
    }
}

Terminal Output:

Mnemonic key code: 83, Tooltip: Click to save student changes to database

7. Setting the Default Enter Key Button for a Form 🔝

You can configure the form to submit automatically whenever the user presses the Enter key:

import javax.swing.*;

public class DefaultEnterButtonDemo {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Login");
        JButton btnLogin = new JButton("Login");
        frame.getRootPane().setDefaultButton(btnLogin);  // Triggered when Enter key is pressed
        System.out.println("Default button set: " + frame.getRootPane().getDefaultButton().getText());
    }
}

Terminal Output:

Default button set: Login

8. Comparison of Java Swing Button Component Types 🔝

Component Behavior Best Used For
JButton Momentary trigger (fires on click) Submit, Cancel, Save, Close actions.
JRadioButton Mutually exclusive single-choice Gender, Payment method, Grading scale.
JCheckBox Independent toggle (checked/unchecked) Agree to terms, remember password options.

» Next Tutorial: Linking Button with TextField and Label

9. Common Developer Pitfalls & Traps 🔝

Blocking the Event Dispatch Thread (UI Freeze)

Executing long-running database queries or file downloads directly inside an actionPerformed method freezes the GUI. Use a background SwingWorker thread for heavy tasks so the button does not become unresponsive!

Using System.exit(0) in Dialog Popups

Calling System.exit(0) terminates the entire Java virtual machine. If your application has multiple windows, always use frame.dispose() to close the active window safely.

10. Complete Compilable Java Program 🔝

public class SwingButtonVerifyDemo {
    public static void main(String[] args) {
        String btnText = "Close window";
        if (btnText.equals("Close window")) {
            System.out.println("All Java Swing JButton verification checks passed!");
        }
    }
}

Terminal Output:

All Java Swing JButton verification checks passed!

11. Frequently Asked Questions (FAQ) 🔝

How do I change the background color of a JButton?

Call button.setBackground(Color.BLUE);. On macOS look-and-feels, you may also need button.setOpaque(true); button.setBorderPainted(false);.

Can I trigger a button click programmatically?

Yes! Calling button.doClick(); simulates a user click and invokes all registered ActionListener instances.

How do I add an icon or image to a JButton?

Pass an ImageIcon: new JButton("Save", new ImageIcon("images/save.png")); or call button.setIcon(...).

What is the difference between addActionListener and addMouseListener?

ActionListener fires specifically when the button is activated (via click, Enter key, or mnemonic); MouseListener tracks low-level events like mouse press, release, enter, and exit.

Where should I go next to read text and display output on button click?

Check out the next tutorial: Linking JButton with JTextField and JLabel.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer