import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class MyButtonActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button clicked!"); } } public class MyGUI { public static void main(String[] args) { // Create a JButton and add an ActionListener JButton myButton = new JButton("Click me!"); myButton.addActionListener(new MyButtonActionListener()); // Add the button to a frame and show the frame MyFrame myFrame = new MyFrame(); myFrame.add(myButton); myFrame.setVisible(true); } }
import javax.swing.JFrame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class MyWindowListener extends WindowAdapter { public void windowClosing(WindowEvent e) { System.out.println("Window closed!"); } } public class MyGUI { public static void main(String[] args) { // Create a JFrame and add a WindowListener JFrame myFrame = new JFrame("My Frame"); myFrame.addWindowListener(new MyWindowListener()); // Show the frame myFrame.setVisible(true); } }In both examples, the EventQueue class is working behind the scenes to manage the event queue and dispatch events to the appropriate components.