In Java, the JFrame class is used to create a window for your graphical user interface (GUI), and the JButton class allows you to add clickable buttons to that window. Here’s a simple guide on how to create a button in a JFrame and handle button click events.
1. Creating a Simple JButton
To create a button inside a JFrame, you need to follow these steps:
- Create an instance of
JFrame
. - Create an instance of
JButton
with a label (text). - Add the button to the JFrame using a layout manager or
add()
method. - Set the JFrame visible and configure basic settings like close operation.
Example:
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
// Create a new JFrame
JFrame frame = new JFrame("JButton Example");
// Create a new JButton with a label
JButton button = new JButton("Click Me!");
// Set JButton size
button.setBounds(50, 70, 200, 20);
// Set the Layout to null
frame.setLayout(null);
// Add the button to the frame
frame.add(button);
// Set the size of the frame
frame.setSize(300, 200);
// Set the default close operation
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make the frame visible
frame.setVisible(true);
}
}
In this example:
- A JFrame named
frame
is created. - A JButton named
button
is created with the label “Click Me!”. - The button is added to the frame using
frame.add(button)
. - The frame is sized to 300×200 pixels, and the window will close when you click the close button.

Conclusion
Creating a JButton
in a JFrame
is a straightforward process. First, create the button and add it to the frame. Then, if you want to handle the button click using an ActionListener
to trigger actions follow this tutorial.
You can further customize the button’s appearance, functionality, and behavior based on your application’s needs.