2

I have a button that I have replaced with an image, on hovering I want the image to play an animated gif. I have added a mouse listener and entered the code for changing the image to the gif. The image changes to the gif; however the gif does not animate. I have had a look for previous answers on this site, there are few but none have been able to help.

        @Override
        public void mouseEntered(MouseEvent arg0) {
            try 
            {
                Image img = ImageIO.read(getClass().getResource("images\\button_1_hover.gif"));
                btnShip1.setIcon(new ImageIcon(img));
            } 
            catch (IOException ex) {}
        }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
sam_7_h
  • 810
  • 3
  • 11
  • 23

1 Answers1

4
  1. Don't use a MouseListener for this, just set up the icon using, setPressedIcon(Icon), setRolloverIcon(Icon) etc. See this answer for an example.
  2. Don't attempt to load the image 'as needed', but instead load them & set them up on the button when it is initialized.
  3. Change
    getClass().getResource("images\\button_1_hover.gif") to
    getClass().getResource("/images/button_1_hover.gif")
  4. Change the method used to load the image. ImageIO will not typically load an animated GIF correctly. See Show an animated BG in Swing for details.
  5. Change code of the form
    catch (Exception e) { .. to
    catch (Exception e) { e.printStackTrace(); // very informative! ..
Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • +1 been a while since I wrote java completely overlooked `/images/...` and the setXXX methods :|! But will `ImageIO.read` make the gif animated? – David Kroukamp Jun 25 '13 at 11:49
  • 1
    @DavidKroukamp No. See [Show an animated BG in Swing](http://stackoverflow.com/q/10836832/418556) for details. – Andrew Thompson Jun 25 '13 at 11:51