Animated ImageIcon as a Button

I have imageIcon as a Button, now I would like to animate it when capsizing. I tried using an animated gif (no loop) on setRolloverIcon (icon). But when I hover the button over the button again, the gif does not play again. When I use a looped gif, it plays it from a random frame. I tried using paintComponent to draw a Shape or image as a Button, which works fine, but even when I use setPreferredSize () or setSize () or setMaximumSize (), Button uses its default size, as you can see in the picture (middle button ) I am using GroupLayout, maybe this is a problem?

enter image description here

+4
source share
1 answer

Everything seems to work just fine for me ...

enter image description hereenter image description here

I used the following icons ... (png and gif) ...

enter image description hereenter image description here

import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.GridBagLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class AnimatedButton { public static void main(String[] args) { new AnimatedButton(); } public AnimatedButton() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { } catch (InstantiationException ex) { } catch (IllegalAccessException ex) { } catch (UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame("Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TestPane extends JPanel { private ImageIcon animatedGif; public TestPane() { setLayout(new GridBagLayout()); JButton btn = new JButton(new ImageIcon("WildPony.png")); btn.setRolloverEnabled(true); animatedGif = new ImageIcon("ajax-loader.gif"); btn.setRolloverIcon(animatedGif); add(btn); btn.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { animatedGif.getImage().flush(); } }); } } } 

I just realized that you are using a non-looping gif. This means that you are going to play with it and "reset" to start playing again.

Try using something like icon.getImage().flush(); where icon is your ImageIcon . You will need to attach a MouseListener to the button to detect the mouseEnter event and reset ImageIcon ...

+5
source

Source: https://habr.com/ru/post/1497405/


All Articles