ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Hacking Swing: Translucent Windows
Pages: 1, 2, 3

Additionally, any user action that would change the screen will probably create lots of events, not just one. It's just the last event that should trigger updateBackground( ), not the first. To handle all these issues, the code creates a thread that watches for repaint requests and only processes a new screenshot if it hasn't already been done in the last 1,000 milliseconds. If the user generates events continuously for five seconds (searching for that lost browser window, for example), then only when everything else has settled down for a second will the refresh actually happen. This ensures that users won't have a window disappear out from under them while they are moving things around.

Another annoyance is that the window still has its border, which sort of ruins the effect of having a transparent background. Unfortunately, removing the borders with setUndecorated(true) would also remove the titlebar and window controls. This probably isn't too much of a problem, though, because the types of applications that typically use shaped windows usually have draggable backgrounds [Hack #34].

Here's a simple test program to put this into action:

public static void main(String[] args) {
    JFrame frame = new JFrame("Transparent Window");
    TransparentBackground bg = new TransparentBackground(frame);
    bg.snapBackground( );
    bg.setLayout(new BorderLayout( ));

   JPanel panel = new JPanel( ) {
        public void paintComponent(Graphics g) { 
            Image img = new ImageIcon("mp3.png").getImage( ); 


    frame.getContentPane( ).add("Center",bg);
    frame.pack( );
    frame.show( );

The code creates a faux MP3 player interface using a JPanel subclass and a PNG image with transparency. Note the call to frame.setUndecorated(true), which turns off the border and titlebar. The call to panel.setOpaque(false) turns off the default background (usually plain gray), allowing the screenshot background to shine through the transparent parts of the image (Figure 6-2). This produces a window that looks like Figure 6-3—a vision of Java programs to come?

Figure 6-2
Figure 6-2. Template for an MP3 player

Figure 6-3
Figure 6-3. Running the MP3 player

Joshua Marinacci is a blogger and co-author of "Swing Hacks" and "Building Mobile Apps with Java" for O'Reilly.

Chris Adamson is an author, editor, and developer specializing in iPhone and Mac.

View catalog information for Swing Hacks

Return to ONJava.com.