views:

237

answers:

4

I know how to draw a rectangle onto a JPanel, but how can I paint a rectangle to the screen so that the rectangle appears to be floating? More specifically, a non-filled rectangle. My thought is to use a transparent JFrame with a rectangle drawn on it; however, this makes all of the content in the JFrame transparent.

My Solution So I think there are many ways of going about this, some more complex than others, some more practical than others.

I tried the splash screen. The problem with that is you need to pass VM parameters "-splash " when you run. I created a manifest file to automate this/put the parameters into eclipse; but then the code is dependent on the .gif file and I can't change the size/position of the rectangle easily. Similar problems occur while faking it via screen screenshot. Good suggestions though, I learned some pretty cool stuff.

So, back to what I did. I used a JFrame, got the content pane and set the background to red (what ever color you want), then set the frame undecorated which removes the titlebar and border of the window. This created a floating rectangle which I could easily change the size and location of (frame.setSize, .setLocation). I have yet to make this a non filled rectangle, I tried internal frames and layeredpanes, but no success.

A: 

You would probably have to have parts of the window transparent while the actual drawn rectangle is not. I doubt there is a platform-agnostic solution for this so you would need to resort to JNI for this. Depending on what you need to do it might also be nice to make the window invisible for clicks which would need other tricks as well.

Joey
A: 

https://jna.dev.java.net/

That project offers a library and has examples of a clock and info balloons that are semi-transparent and transcend even what you're trying to do. The demos work well on Windows but I couldn't speak to how cross platform they are.

John Munsch
+1  A: 

JFrame is a heavyweight component, and those were always opaque for the longest time. However, since Java 6u10, there is an inofficial API for transparent windows in the class com.sun.awt.AWTUtilities, which will most likely become official in Java 7. In earlier versions, the only way to simulate this kind of thing was to fake it via screenshots taken with java.awt.Robot

Michael Borgwardt
A: 

You might want to look at JLayeredPane. The demo on this page shows partially what you want, however when painting your rectangle you'll need to set your paint to transparent:

AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
g2d.setComposite(ac);
g2d.drawImage(image, x, y, this);
Pool