I have created an array of buttons (JButton[] jb = new JButton[100]
) and I want to add the same action listener for all the buttons in the jb
array instead of adding them one by one.
Just imagine every time I click one of the buttons displayed on the screen and it will print out the index of that button in the jb
array.
CodePudding user response:
The trivial answer is yes, you can add the same listener to many different buttons, and via the parameter the listener will be able to figure out which Button instance clicked it.
The challenge is that you won't be able to know which index in the array matches the button, so you'll need to either:
- Figure out which button it was based on something in the button, like its
getLabel
value - Scan the array each click to figure out the index for a button instance, which is slow (
O(n)
), but for a hundred buttons it might not matter that much - Store a mapping from button instance to array index in a different faster data structure like a HashMap (
O(1)
), which might get ugly if buttons aren't well defined to be hashable - Use the same ActionListener class for all the buttons, but store a field on each instance of the listener that tells it what index it maps to