William
William

Reputation: 8818

Drawing non-transparent content on transparent window

So I'm trying to draw a solid red oval on a transparent window. I later want to do something more complex with multiple shapes, so using setWindowShape isn't what I'm looking for. This is the code I'm using so far:

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();
     }
}

Upvotes: 2

Views: 2339

Answers (2)

Durandal
Durandal

Reputation: 20069

You are applying a global transparency to you window, so naturally everything in it will be at least as transparent as the global value. You probably want per-pixel translucency. Replace

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

with

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

This leaves just your oval visible and it will be completely opaque. More infos can be found in this Tutorial

Upvotes: 4

camickr
camickr

Reputation: 324207

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

Code doesn't look quite right. I would try:

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

or just use:

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

Upvotes: 0

Related Questions