2012-10-13 31 views
5
Icon icon = new ImageIcon(getClass().getResource("/img/icon.gif")); 
aButton = new JButton("Its a button", icon); 

是否有某種方法可以阻止播放動畫? 我正在考慮分配gif的靜態jpg,然後當我懸停時,分配動畫gif,但我不認爲在MouseMotionListener中有一個脫掉鼠標的事件,所以我可以加載靜態jpg。GIF動畫上一個JButton,玩時,鼠標懸停

但是,如果我將鼠標懸停在按鈕上,它會消失。

如果我的鼠標光標不在按鈕上,我該如何使gif靜態?

如果我使用MouseMotionListener,如果我摘下鼠標,它會觸發一個事件嗎?

@Override 
public void mouseMoved(MouseEvent e) { 
//play the gif 
//if I take mouse off, call some method to stop playing animated gif 
} 

@Override 
public void mouseDragged(MouseEvent e) { 
} 

回答

5

參見:

無需設置顯式鼠標偵聽器,切換將自動進行。

E.G.在這個例子中,我沒有添加MediaTracker,因此將圖像彈出到標籤中以允許加載時間。最終用戶是ImageObserver(等到您在解散第一個對話框之前看到它旋轉)。

import java.awt.*; 
import java.awt.image.BufferedImage; 
import java.net.URL; 
import javax.swing.*; 

public class ImageSwapOnButton { 

    public static void main(String[] args) throws Exception { 
     URL url = new URL("http://1point1c.org/gif/thum/plnttm.gif"); 

     Image image = Toolkit.getDefaultToolkit().createImage(url); 
     ImageIcon spinIcon = new ImageIcon(image); 
     JOptionPane.showMessageDialog(null, new JLabel(spinIcon)); 

     // create a static version of this icon 
     BufferedImage bi = new BufferedImage(150,150,BufferedImage.TYPE_INT_ARGB); 
     Graphics g = bi.getGraphics(); 
     g.drawImage(image,0,0,null); 
     g.dispose(); 
     ImageIcon staticIcon = new ImageIcon(bi); 

     JButton button = new JButton(staticIcon); 
     button.setRolloverIcon(spinIcon); 
     JOptionPane.showMessageDialog(null, button); 
    } 
} 

另外,不要將靜態圖像製作爲JPEG。 JPEG是有損的,不支持透明度。可以使用單個幀GIF或PNG。

+2

@Lan試着用'ImageIO'生成一個[GIF動畫](http://stackoverflow.com/questions/10836832/show-an-animated-bg-in-swing)。 ;) –

+1

感謝您的鏈接,我學到了一些新東西。 – LanguagesNamedAfterCofee

+0

@Lan當我偶然發現它的時候,這讓我感到驚訝!我經常爲非動畫圖像使用'ImageIO',並且我需要動畫GIF的場合通常是處理所有'自動'處理的組件(按鈕,組件中的HTML等)。儘管我通過文檔進行了漫遊,但我無法找到解釋爲什麼'ImageIO'不*生成動畫GIF。 –

-1
button.setIcon(new ImageIcon("/*icon location*/")); 
button.setRolloverIcon(new ImageIcon("/*icon location*/" 

當鼠標指針移動到按鈕上時,Animated gif圖像不會隱藏。

相關問題