2013-08-16 81 views
4

我有一個imageIcon作爲按鈕,現在我想在你翻轉時爲它設置動畫。我試圖在setRolloverIcon(Icon)上使用動畫gif(沒有循環)。但是當我再次將鼠標懸停在按鈕上時,gif不再播放。當我使用循環的gif時,它會從隨機幀中播放它。我嘗試使用paintComponent來繪製一個Shape或一個圖像作爲按鈕,它工作正常,但即使當我使用setPreferredSize()或setSize()或setMaximumSize()時,按鈕使用其默認大小,如圖所示(中間按鈕)。我使用GroupLayout,這可能是問題嗎?動畫ImageIcon作爲按鈕

enter image description here

+0

GIF動畫將無法正常工作。你需要使用多個圖像作爲框架。 – Ashwani

+0

我以爲它需要像精靈一樣。那麼我試過了,但按鈕仍然使用它的默認大小,如圖所示。 – domizai

回答

5

似乎只是正常工作對我來說...

enter image description hereenter image description here

我用下面的圖標...(PNG和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(); 
       } 

      }); 
     }  
    } 
} 

我剛剛意識到你正在使用一個非循環的gif。這意味着您將要嘗試「重置」以重新開始播放。

嘗試使用類似icon.getImage().flush();的東西,其中icon是您的ImageIcon。你將不得不附加一個MouseListener到按鈕來檢測mouseEnter事件和重置ImageIcon ...

+0

請你測試一下我的代碼,因爲它不起作用,你的或我的也可以用 – mKorbel

+0

@mKorbel而不是使用'button.setIcon(null)',你可以嘗試使用'icon.getImage()。flush()',這將強制JVM重新加載圖標,並開始播放它... – MadProgrammer

+0

不是我嘗試刷新(),試圖重寫BasicButtonUI,對於MetalLaF將無法正常工作,缺少一些通知 – mKorbel