Mastering Java Swing
Interactivity with JButtons
Basic Java Swing ElementsJButton allows users to perform actions by clicking on it. We’ll explore how to create a button and make it respond to clicks.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("JButton Example");
JPanel panel = new JPanel();
JButton button = new JButton("Click Me!");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button was clicked!");
}
});
panel.add(button);
frame.add(panel);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}Members only
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 27 more lessons in Mastering Java Swing.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.