【问题标题】:Drawing non-transparent content on transparent window在透明窗口上绘制非透明内容
【发布时间】:2010-10-31 15:52:37
【问题描述】:

所以我试图在透明窗口上绘制一个实心红色椭圆。后来我想用多个形状做一些更复杂的事情,所以使用 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();
     }
}

【问题讨论】:

  • 我不确定我是否理解这个问题。我看到了红色的椭圆形。我无法访问 AWTUtilities,所以也许这就是区别。
  • 确实如此。窗口应该是透明的,但椭圆必须是不透明的。
  • +1:我也问过。并且仍在寻找一个好的解决方案。 stackoverflow.com/questions/3372016/…

标签: java swing graphics transparency


【解决方案1】:

您正在对窗口应用全局透明度,因此其中的所有内容自然至少与全局值一样透明。您可能需要每像素半透明。替换

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

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

这只会使您的椭圆形可见,并且将完全不透明。更多信息可以找到in this Tutorial

【讨论】:

  • 改变给了我这个:线程“main”java.lang.IllegalArgumentException中的异常:不支持装饰窗口的效果。
  • 奇怪,您使用的是什么平台和 JRE 版本?我粘贴了您的代码并更改了行(WinXP 上的 Sun JDK 1.6.0_18)。
【解决方案2】:
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);   

【讨论】:

  • 这些都不起作用,奇怪的是使用 g 而不是 g.create() 使椭圆从黑色变为红色。
猜你喜欢
  • 2010-09-13
  • 2021-04-10
  • 1970-01-01
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 2018-08-12
  • 2013-02-21
  • 2018-07-06
相关资源
最近更新 更多