import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class SimpleButton extends JFrame implements ActionListener { private JButton button; public SimpleButton() { setTitle("Simple Button Example"); setDefaultCloseOperation(EXIT_ON_CLOSE); JPanel panel = new JPanel(); button = new JButton("Click me!"); button.addActionListener(this); // Register an action listener panel.add(button); add(panel); pack(); setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource() == button) { System.out.println("Button clicked!"); } } public static void main(String[] args) { new SimpleButton(); } }
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class DisableButton extends JFrame implements ActionListener { private JButton button; public DisableButton() { setTitle("Disable Button Example"); setDefaultCloseOperation(EXIT_ON_CLOSE); JPanel panel = new JPanel(); button = new JButton("Click me!"); button.addActionListener(this); // Register an action listener panel.add(button); add(panel); pack(); setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource() == button) { button.setEnabled(false); // Disable the button } } public static void main(String[] args) { new DisableButton(); } }This example creates a GUI with a single button that says "Click me!". When the user clicks the button, an event is triggered which disables the button by calling the setEnabled() method with a parameter of false. Both examples use the java.awt.event package library.