Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - the ol' transparent JFrame, without restricted libs

Yes, this question is everywhere. But all of the (working) solutions use the AWTUtilities toolkit, which is restricted.

So. I just want to control the opacity of my window. No need to shape or undecorate. Just a transparent contentPane (easy), and a transparent JFrame background (ridiculously difficult).

I could have sworn I got the right combination of stuff yesterday, but now I can't seem to reproduce it. Also there are some solutions out there without using AWTUtilities, but they don't work...does someone have a good solution?

An example of my failing code:

public static void main(String[] args) {
    JFrame test = new JFrame();
    test.setSize(400, 400);
    test.setLocationRelativeTo(null);
    test.setUndecorated(true);
    test.setBackground(new Color(0, 0, 0, 0));
    test.getContentPane().setBackground(new Color(0,0,0,0));
    test.setVisible(true);
}

but this just makes a white square. Close but no cigar. I've also tried overriding the paint method, and someone was saying something about throwing out the alpha channel, but that made it black (of course). So...Stack Overflow it is.

If there's a dupe that answers this exactly, please point me to it and I'll delete right away.

Update Per requests in comments, here's a history of how I arrived here:

The first link everyone arrives at is how to create translucent and shaped windows. This has several lines in there similar to "...the frame translucent with a 75% level of opacity." So...looks like they're defined the same, at least in that article. Unfortunately they use the library.

A couple links that I could chase down:

A non-working "working" solution is reported at http://www.java-gaming.org/index.php?topic=24635.0 which shows some hope but I couldn't get it working.

http://techgearup.wordpress.com/2008/09/19/transparent-jframe-background/ is a hackish way using screenshots and is duplicated in a few other places.

like image 399
Ben Avatar asked Nov 14 '22 16:11

Ben


1 Answers

You can't do this without using Java v.6u10+ or third-party libraries that call native code. In Swing Frames, Dialogs, and Windows are considered 'top-level components' and are rendered in the underlying windowing system. Before Java v6u10, all top-level components had a default, opaque light-grayish background, and there was no way to change this from Java code.

like image 113
Nate Avatar answered Dec 18 '22 22:12

Nate