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.
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:
getLabel
valueO(n)
), but for a hundred buttons it might not matter that muchO(1)
), which might get ugly if buttons aren't well defined to be hashable