Changing The Underlying Background Color Of A Swing Window

dimo414 picture dimo414 · May 6, 2010 · Viewed 14k times · Source

As discussed here, when resizing a Swing application in Vista (and Windows 7, which is what I'm using) you get a black background in the right/bottom corner while Swing's repaint catches up to the changes.

Playing with other applications (Windows Explorer (Native), Firefox (C++?), and Eclipse (Java)) I notice that they all have this same problem - contrary to what the folks in the link above say - but they minimize the problem by having a grey fill color, which is far less visually jarring than the black that appears in Swing.

I'm wondering if there's some way to change this so that Swing behaves like these other applications? I tried setting the background color of the JFrame, but to no avail.

Additional Info Jonas discovered (see their informative answer below) that this is an issue with JFrames, but not AWT Frames - maybe that will help someone figure this out.

Answer

Jonas picture Jonas · May 6, 2010

I have noticed the same problem. This color is gray at IE, in Opera it's black, and in Eclipse it's gray. It seam to be more visible in Swing, because it seam to be little slower at repainting and the color is as you said, black. This problem is more visible if you use the upper left corner to resize.

I coded an example and tried to understand where this black color is defined. A JFrame has many layers, so I set a different background on every layer.

import java.awt.Color;
import javax.swing.JFrame;

public class BFrame {

    public static void main(String[] args) {
        new JFrame() {{
            super.setBackground(Color.CYAN);
            this.getRootPane().setBackground(Color.BLUE);
            this.getLayeredPane().setBackground(Color.RED);
            this.getContentPane().setBackground(Color.YELLOW);
            this.setSize(400,340); 
            this.setVisible(true);
        }};
    }
}

But this example didn't help. And maybe the color is set by a superclass to Frame.

java.lang.Object
  java.awt.Component
      java.awt.Container
          java.awt.Window
              java.awt.Frame

My teory is that, since Swing paints itself, but uses a native Window, then is the native background painted before the resize, and the background of Swing is painted after the resize. But for native applications, the background is painted before the resize.

UPDATE: I tried with a Frame now, and it's not having the same problem. The background seam to be painted before the resize.

import java.awt.Color;
import java.awt.Frame;

public class B2Frame extends Frame {

    public static void main(String[] args) {
        new Frame() {{
            setBackground(Color.YELLOW);
            setSize(400,340);
            setVisible(true);
        }};
    }

}