JavaNewbie_M107
JavaNewbie_M107

Reputation: 2037

Can I add an ActionListener to a JPanel

I am creating a swing program which basically has a lot of buttons, and I was thinking that instead of adding the listener individually to each button, if I could add the listener to the JPanel instead, and read the events using .getSource() function, things would be a whole lot easier? Is it possible?

Upvotes: 2

Views: 2298

Answers (3)

mKorbel
mKorbel

Reputation: 109813

I am creating a swing program which basically has a lot of buttons, and I was thinking that instead of adding the listener individually to each button, if I could add the listener to the JPanel instead, and read the events using .getSource() function, things would be a whole lot easier? Is it possible?

not possible to add ActionListener, only MouseListener can do that, but not correct way for JButton

depends of your code, you have to add ActionListener to every JButtons and to determinte which one is pressed by

  • put/getClientProperty

  • ActionCommand

  • programatically loop instide arrays of JButtons and to compare event and JButton

Upvotes: 2

Juvanis
Juvanis

Reputation: 25950

Adding a listener to a component doesn't mean that you are also adding that listener to the internal components. Instead, think of using groups of buttons (e.g. a button array) and add the listener to all buttons with one iteration.

for(JButton button : buttonsArray)
    button.addActionListener(yourActionListener);

Upvotes: 5

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

No, you can not, take a look on documentation

If all your buttons have the same listener behavior, add them to ArrayList<JButton> and in loop add the same instance of ActionListener

Upvotes: 1

Related Questions