I have a frame and it has to listen to button press whatever element is selected. Is it possible to make a global listener for this frame, or I have to write listeners for every element I have?
Listener for button press wherever in the frame
72 views Asked by crzbt At
2
There are 2 answers
0
On
I'm not sure this is what you want. You can make those buttons use the same action listener,
//set up some buttons...
bt1 = new JButton("BUTTON1");
bt2 = new JButton("BUTTON2");
//use the same actionListener
bt1.addActionListener(someActionListener);
bt2.addActionListener(someActionListener);
then in actionPerformed method you can check which button was pressed.
public void actionPerformed(ActionEvent e){
JButton pressedButton = (JButton)e.getSource();
//check which button was pressed
if(pressedButton ==bt1)
System.out.println("Button 1 do something");
else if(pressedButton ==bt2)
System.out.println("Button 2 do something");
}
Write a MouseListener/MouseAdapter and share the same instance with all the elements you want to react to.
This other question will give you a clue: Java MouseListener