Search code examples
javaswingjbuttonjlabelimageicon

Programmatically change ImageIcon automatically [Java]


I am making a simple game right now. When a JButton is clicked, the ImageIcon of a JLabel is supposed to change. How can I accomplish this?


Solution

  • Simple, just quickly run setIcon() on the JLabel via the action listener of the button.

    An example:

      if ("burp".equals(evt.getActionCommand())) {
            charLabel.setIcon(burpIcon);
            Sounds.burp();
      }
    

    As mentioned by MadProgrammer, any issue you have seeing real-time changes to setIcon() will probably warrant a look at how you've actually designed the class, rather than attempting a hacky workaround to force the ImageIcon to function as it should with the proper setup.