One method you can try is to set an action command on the button when it is created. This java tutorial demonstrates this concept is greater detail.
In your case, you would set it like so:
final JButton iconButton = new JButton(icon);
iconButton.setActionCommand("some_unique_identifying_information");
And you can retrieve it in the actionPerformed
callback like so:
@Override
public void actionPerformed(ActionEvent e) {
String actionCommand = iconButton.getActionCommand();
// ... rest of method
}
Note the use of final
on the iconButton. From the looks of your code, the button that fires the event is accessible via the action listener's closure. If you prefer, or cannot use the above method, you can access the button like so:
@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
String actionCommand = button.getActionCommand();
// ... rest of method
}
Similar to Christian's suggestion in the comments, you can, if you wish, maintain a Map
or other data structure in which your unique action command is related to an image. Your map might look like Map<String, ImpImage>
(assuming ImpImage
is the class of your icon).
Alternatively, the action command may be the string representation of your index value. While it must be stored in String
form, once you retrieve it via getActionCommand()
, you can parse it back to a number using Integer.parseInt(String)
.