Practical No 21 :
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActionEventExample extends JFrame implements ActionListener {
private JButton button1, button2;
public ActionEventExample() {
// Setting up the frame
setLayout(new FlowLayout());
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Creating buttons
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
// Adding action listeners to the buttons
button1.addActionListener(this);
button2.addActionListener(this);
// Adding buttons to the frame
add(button1);
add(button2);
setVisible(true);
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
System.out.println("Button 1 clicked");
} else if (e.getSource() == button2) {
System.out.println("Button 2 clicked");
public static void main(String[] args) {
new ActionEventExample();
}
Output: