2012-04-13 82 views
2

我得到了白色的圖標,當我穿過那個圖標時,我想做出不同的顏色。如何更改鼠標上的圖標?

這裏是我的圖標是白色:

hint.setIcon(newjavax.swing.ImageIcon(getClass().getResource ("white.png"))); 

我怎麼能當你拖動鼠標移到圖標改變顏色做什麼呢?

回答

8

我懷疑這個問題的答案是在未修飾的按鈕中。將白色圖像設置爲圖標,將黃色圖像設置爲roll-over icon。像這樣:

import java.awt.*; 
import javax.swing.*; 
import java.net.URL; 
import javax.imageio.ImageIO; 

class HoverImage { 

    HoverImage(Image img1, Image img2) { 
     JButton b = new JButton(new ImageIcon(img1)); 
     b.setRolloverIcon(new ImageIcon(img2)); 

     b.setBorderPainted(false); 
     b.setContentAreaFilled(false); 

     JOptionPane.showMessageDialog(null, b); 
    } 

    public static void main(String[] args) throws Exception { 
     URL url1 = new URL("https://i.stack.imgur.com/XZ4V5.jpg"); 
     URL url2 = new URL("https://i.stack.imgur.com/7bI1Y.jpg"); 
     final Image img1 = ImageIO.read(url1); 
     final Image img2 = ImageIO.read(url2); 
     //Create the frame on the event dispatching thread 
     SwingUtilities.invokeLater(new Runnable(){ 
      @Override 
      public void run() { 
       new HoverImage(img1, img2); 
      } 
     }); 
    } 
} 
+2

參考這個相關的[示例](http://stackoverflow.com/a/4170233/230513)。 – trashgod 2012-04-13 20:43:42

+0

'Hint.setRolloverIcon(「yellow.png」)';我使用該代碼,它的工作原理是corectlly – 2013-10-28 13:08:35