Summary: in this tutorial, you will learn how to create a push button in Swing using the JButton
class.
Creating a button using JButton
The button is one of the simplest UI components, which is used to generate events when the user clicks or presses on it. In swing, a button can display text, an icon, or both.
The state of the Swing button is maintained by the ButtonModel
object. The ButtonModel
interface defines methods for reading and writing model’s properties or adding and removing event listeners.
There is an implementation of the ButtonModel
interface called DefaultButtonModel
. The DefaultButtonModel
is used directly by the AbstractButton
class. The AbstractButton
is the base class for all Swing button components (JButton
, JToggleButton
, JCheckbox
, JRadioButton
, and JMenuItem
).
The following program shows you how to use JButton
class to create simple buttons and add event handlers:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Button Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
// Create panel to hold buttons
JPanel buttonPanel = new JPanel();
frame.add(buttonPanel, BorderLayout.SOUTH);
// Create and add OK button
JButton btnOK = new JButton("OK");
btnOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame,
"You've clicked the OK button");
}
});
buttonPanel.add(btnOK);
// Create and add Cancel button
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame,
"You've clicked the Cancel button");
}
});
buttonPanel.add(btnCancel);
// Center the frame on the screen
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Code language: Java (java)
How it works.
- Create a new instance of
JButton
class. In this case, we create a new button and pass the text to display on that button which is “OK
” and “Cancel”. - To add an event handler for the button, use the method
addActionListener
. You see we create an anonymous class as a parameter of the method. We put our code to handle the event inside the methodactionPerformed
. In this case, we show a message dialog to notify that the user has clicked the corresponding button. - Then we add buttons to a panel and add this panel to the frame.
Summary
- Use the
JButton
class to create a push button.