[英]How to create partly transparent JButton on fully transparent JFrame?
我能夠使JFrame完全透明,JButton部分透明,直到我在按鈕上移動鼠標(不要單擊)並從按鈕移開鼠標(通過MouseListener調用MouseExited)。 會發生什么是JButton的背景再次被繪制,所以在按鈕上打開和關閉幾個鼠標后,按鈕完全不透明。
public class ButtonExample extends JWindow
{
public ButtonExample( )
{
JButton But = new JButton( "Testing" );
But.setBackground( new Color( 0, 0, 0, 200 ) );
But.setForeground( new Color( 70, 155, 255 ) );
this.add( But );
this.setBackground( new Color( 0, 0, 0, 0 ) );
this.setMinimumSize( new Dimension( 200,100 ) );
this.setVisible( true );
}
public static void main( String[ ] Args )
{
new ButtonExample( );
}
}
問題是按鈕報告完全不透明,實際上它不是(由於部分透明的顏色)
but.setOpaque(false);
BTW:如你所見,我改變了字段名稱以符合java命名約定:-)
編輯
arggghh ..錯過了,對不起。 需要檢查我們在SwingX中做什么,從頭頂我會說你需要覆蓋paintComponent並自己處理背景畫,比如
/**
* @inherited <p>
*/
@Override
protected void paintComponent(Graphics g) {
if (!isOpaque() && getBackground().getAlpha() < 255) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g);
}
但是,沒有嘗試,也許“變得越來越不透明”又回來了。明天會回來
編輯2
好的,檢查 - 編輯的代碼正常工作。 總結:具有半透明背景的組件
為了您的方便,這里是一個小型的可運行的,並排不正確/正確的背景
public class TransparentButton {
public TransparentButton() {
JWindow incorrectOpaque = createWindow("incorrect opaque", true);
incorrectOpaque.setLocation(600, 600);
incorrectOpaque.setVisible(true);
JWindow correctOpaque = createWindow("correct opaque", false);
correctOpaque.setLocation(800, 600);
correctOpaque.setVisible(true);
}
private JButton createButton(final boolean opaque) {
JButton but = new JButton("Testing") {
/**
* @inherited <p>
* Overridden to take over background painting with
* transparent color.
*/
@Override
protected void paintComponent(Graphics g) {
if (!isOpaque() && getBackground().getAlpha() < 255) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g);
}
};
but.setBackground(new Color(0, 0, 0, 100));
but.setForeground(new Color(70, 155, 255));
but.setOpaque(opaque);
return but;
}
private JWindow createWindow(String text, boolean opaque) {
JWindow window = new JWindow();
JButton but = createButton(opaque);
window.add(but);
window.add(new JLabel(""), BorderLayout.SOUTH);
window.setOpacity(0.5f);
window.setBackground(new Color(0, 0, 0, 0));
window.setSize(new Dimension(200, 100));
return window;
}
public static void main(String[] Args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TransparentButton();
}
});
}
@SuppressWarnings("unused")
private static final Logger LOG = Logger.getLogger(TransparentButton.class
.getName());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.