This is my first class where I add the 2 JButtons and pass the object of MyHandler class handler to the 2 buttons.
import javax.swing.*;
import java.awt.*;
public class Buttons {
JButton b1, b2;
public Buttons() {
GridBagConstraints gbc = new GridBagConstraints();
JFrame frame = new JFrame("Frame 1");
frame.setLayout(new GridBagLayout());
frame.setSize(500, 500);
MyHandler handler = new MyHandler();
b1 = new JButton("Button 1");
b1.addActionListener(handler);
b2 = new JButton("Button 2");
b2.addActionListener(handler);
gbc.gridx = 0;
gbc.gridy = 0;
frame.getContentPane().add(b1, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
frame.getContentPane().add(b2, gbc);
// Make the program quit on close
frame.addWindowListener(handler);
frame.setVisible(true);
}
}
This is MyHandler class, which extends WindowAdapter class which is used to quit the program after closing and it also implements the ActionListener interface from which the actionPerformed method is overridden
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyHandler extends WindowAdapter implements ActionListener{
public void windowClosing(WindowEvent e){
System.exit(0);
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("message");
if(e.getSource() == b1){
}
}
}
Now, it does recognize when I click on either of the 2 buttons, but I am having trouble recognizing the specific button that was clicked.
the line if(e.getSource() == b1){} gives me an error on 'b1', which makes sense since its in another class. Is there any wait to make it work, maybe creating an object of the Buttons class?
Thank You.