0

In Java Swing, is there a quick way to change the icon of whichever button was pressed without having to write it separately for each button. Something like

event.getSource().setIcon( icon );

But this came up with a "cannot find symbol" error. Is there a way to do this?

Thanks in advance

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
DalekCaan99
  • 51
  • 1
  • 8

1 Answers1

2

Yes, that will work, but understand that getSource() returns an Object, and so you will need to cast, and cast carefully.

e.g.,

((JButton) event.getSource()).setIcon(icon);

If you're using a "switchboard" type of listener, where the listener is used on many different items (not really recommended that you do), then you'll need to check the type of the source before casting to avoid a casting exception.

If this doesn't work, you will need to be much more specific about "does not work" (not a very helpful phrase for us).

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373