2010-10-31 113 views
2

所以我試圖在透明窗口上繪製一個堅實的紅色橢圓。我後來想要做更復雜的多個形狀的東西,所以使用setWindowShape不是我要找的東西。這是我使用至今代碼:在透明窗口上繪製非透明內容

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

public class JavaDock extends JFrame{ 

    public JavaDock(){ 
     super("This is a test"); 

     setSize(400, 150); 

     setUndecorated(true); 
     getContentPane().setLayout(new FlowLayout()); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JPanel panel = new JPanel() 
     { 
      public void paintComponent(Graphics g) 
      { 
       Graphics2D g2d = (Graphics2D) g.create(); 
       g2d.setComposite(AlphaComposite.Clear); 
       g.setColor(Color.red); 

       //Draw an oval in the panel 
       g.fillOval(10, 10, getWidth() - 20, getHeight() - 20); 
      } 
     }; 

     panel.setOpaque(false); 
     setGlassPane(panel); 
     getGlassPane().setVisible(true); 
     com.sun.awt.AWTUtilities.setWindowOpacity(this, 0.5f); 
     setVisible(true); 
    } 

    protected void paintComponent(Graphics g) { 

     } 

    public static void main(String[] args){ 
     JavaDock jd = new JavaDock(); 
    } 
} 
+0

我不確定我是否理解這個問題。我看到了紅色的橢圓形。我無法訪問AWTUtilities,所以也許這是不同的。 – camickr 2010-10-31 16:01:01

+0

確實如此。該窗口被認爲是透明的,但橢圓形需要是不透明的。 – William 2010-10-31 16:04:55

+0

+1:我也問過。並仍在尋找一個好的解決方案。 http://stackoverflow.com/questions/3372016/java-transparent-windows-with-non-transparent-components – 2010-11-07 13:25:39

回答

0
Graphics2D g2d = (Graphics2D) g.create(); 
g2d.setComposite(AlphaComposite.Clear); 
g.setColor(Color.red); 
g.fillOval(10, 10, getWidth() - 20, getHeight() - 20); 

代碼看起來不完全正確。我會嘗試:

Graphics2D g2d = (Graphics2D)g; 
g2d.setComposite(AlphaComposite.Clear); 
g2d.setColor(Color.red); 
g2d.fillOval(10, 10, getWidth() - 20, getHeight() - 20); 

或只使用:

g.setColor(Color.red); 
g.fillOval(10, 10, getWidth() - 20, getHeight() - 20); 
+0

沒有那些工作,奇怪的是使用g而不是g.create()使橢圓從黑色變爲紅。 – William 2010-10-31 16:18:34

4

你申請一個全球性的透明度,以你的窗口,自然一切都在它至少會爲全球價值爲透明。您可能需要每像素半透明。更換

com.sun.awt.AWTUtilities.setWindowOpacity(this, 0.5f); 

com.sun.awt.AWTUtilities.setWindowOpaque(this, false); 

這將使只是你的橢圓形可見,這將是完全不透明。更多信息可以發現in this Tutorial

+0

更改,給了我這個: 線程「主」java.lang.IllegalArgumentException異常:不支持裝飾窗口的影響。 – William 2010-11-05 18:45:06

+0

奇怪,您使用的平臺和JRE版本是什麼?我粘貼了你的代碼,只是改變了行(WinXP上的Sun JDK 1.6.0_18)。 – Durandal 2010-11-05 20:11:55