2012-04-06 122 views
0

我想製作一個透明的按鈕,直到用戶將鼠標移動到它上面爲止,所以我創建了自己的類來擴展JButton。我對它進行了測試,它確實使按鈕透明,並且在用戶懸停時發現並檢測到按鈕,但不會使其不透明。我需要使用此代碼更改哪些內容?JButton子類不會改變透明度

import javax.swing.*; 
import java.awt.event.*; 

public class TransparentButton extends JButton { 

    boolean opaque = false, areaFilled = false, borderPainted = false; 

    public TransparentButton(Icon icon) { 
     super(icon); 
     initialise(); 
    } 

    public TransparentButton(String text) { 
     super(text); 
     initialise(); 
    } 

    private void initialise() { 
     super.setOpaque(opaque); 
     super.setContentAreaFilled(areaFilled); 
     super.setBorderPainted(borderPainted); 
     super.addMouseListener(new MouseListener() { 
      public void mouseEntered(MouseEvent e) { 
       opaque = true; 
       areaFilled = true; 
       borderPainted = true; 
      } 

      public void mouseExited(MouseEvent e) { 
       opaque = false; 
       areaFilled = false; 
       borderPainted = false; 
      } 

      public void mouseClicked(MouseEvent e) {} 
      public void mousePressed(MouseEvent e) {} 
      public void mouseReleased(MouseEvent e) {} 
     }); 
    } 
} 

回答

1
import javax.swing.*; 
import java.awt.event.*; 

public class TransparentButton extends JButton { 

    boolean opaque = false, areaFilled = false, borderPainted = false; 

    public TransparentButton(Icon icon) { 
     super(icon); 
     initialise(); 
    } 

    public TransparentButton(String text) { 
     super(text); 
     initialise(); 
    } 

    private void initialise() { 

     super.addMouseListener(new MouseListener() { 
      public void mouseEntered(MouseEvent e) { 
       opaque = true; 
       areaFilled = true; 
       borderPainted = true; 
       reset(); 

      } 

      public void mouseExited(MouseEvent e) { 
       opaque = false; 
       areaFilled = false; 
       borderPainted = false; 
       reset(); 
      } 

      public void mouseClicked(MouseEvent e) {} 
      public void mousePressed(MouseEvent e) {} 
      public void mouseReleased(MouseEvent e) {} 
     }); 
    } 

    private void reset() { 
     super.setOpaque(opaque); 
     super.setContentAreaFilled(areaFilled); 
     super.setBorderPainted(borderPainted); 
    } 
} 
+0

謝謝。這很有道理! – sticks 2012-04-06 08:49:59

0

設置變量是不夠的。您也必須在按鈕上調用適當的方法:

 public void mouseEntered(MouseEvent e) { 
       super.setOpaque(true); 
       super.setContentAreaFilled(true); 
       super.setBorderPainted(true); 

     } 

     public void mouseExited(MouseEvent e) { 
       super.setOpaque(false); 
       super.setContentAreaFilled(false); 
       super.setBorderPainted(false); 

     } 

P.S:我沒有測試它。但這似乎在邏輯上顯而易見enoguh

1

boolean opaque = false,areaFilled = false,borderPainted = false; 字段不透明,areaFilled和borderPainted是您的會話的局部變量。 改變它不會影響晚餐類!

有大量的邏輯setOpaque,setContentAreaFilled的後面,setBorderPainted方法 你應該使用它

相關問題