简体   繁体   中英

Animated gif does not play - mouse listener - event mouse entered

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) {}
        }
  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! ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM