JButton: Clickable Actions in Swing
JButton represents a clickable button. When the user presses it, an action can be performed (handled via event listeners in later sections).
Example: Multiple JButtons in a Frame
This example creates three buttons and adds them to the frame usingFlowLayout, which arranges them in a horizontal row.
import javax.swing.*;
import java.awt.*;
class MyFrame extends JFrame {
MyFrame() {
setTitle("Components - JButton");
// Defining Buttons using JButton
JButton b1 = new JButton("Button 01");
JButton b2 = new JButton("Button 02");
JButton b3 = new JButton("Button 03");
// adding buttons to the frame:
add(b1);
add(b2);
add(b3);
// Default Frame:
setLayout(new FlowLayout()); // General Flow Layout
setVisible(true);
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class JButtonDemo {
public static void main(String[] args) {
new MyFrame();
}
}What is JButton?
JButton is a push button that users can click to trigger an action. We will later attach event listeners to respond when a button is pressed.
- Can contain text, icons, or both.
- Often used for actions like Submit, Cancel, Next, etc.
- Generates events that your code can handle using listeners.
Line-by-line: Understanding the JButton example
Again, the JFrame setup is the same pattern. Here we look at how the buttons are created and laid out.
JButton b1 = new JButton("Button 01");
JButton b2 = new JButton("Button 02");
JButton b3 = new JButton("Button 03");
Creates three separate button objects with different labels. Each button can later have its own behavior.
add(b1);
add(b2);
add(b3);
Adds all three buttons to the frame. The layout manager determines where and how they appear.
setLayout(new FlowLayout());
Uses FlowLayout, which places the buttons next to each other in a row, wrapping to the next line if there is not enough space.
Buttons in real applications
In real projects, buttons are connected to event listeners. For exam programs, it's enough to show how to create and place buttons. In later sections we will handle clicks and perform actions.