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)]
To place buttons precisely using coordinates (see setBounds() Tutorial), first assign Absolute Layout to your content pane in Eclipse WindowBuilder:
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:

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
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:

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.
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
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
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
| 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
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!
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.
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!
Call button.setBackground(Color.BLUE);. On macOS look-and-feels, you may also need button.setOpaque(true); button.setBorderPainted(false);.
Yes! Calling button.doClick(); simulates a user click and invokes all registered ActionListener instances.
Pass an ImageIcon: new JButton("Save", new ImageIcon("images/save.png")); or call button.setIcon(...).
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.
Check out the next tutorial: Linking JButton with JTextField and JLabel.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.