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?
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 (eg a button array) and add the listener to all buttons with one iteration.
for(JButton button : buttonsArray)
button.addActionListener(yourActionListener);
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.