Changing The Underlying Background Color Of A Swing Window

后端 未结 3 700
庸人自扰
庸人自扰 2020-12-30 06:16

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

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-30 06:20

    The frame is responsible for painting its background so you need to make sure you let it do its job.

    You demonstrate this by setting:

    System.setProperty("sun.awt.noerasebackground", "true");
    

    This will cause the background to always be black on resize expansions. (So don't do it.)

    The following worked for me:

    1. (AWT only) Set up double buffering using createBufferStrategy(2) - wrapped in addNotify() otherwise you'll run into exceptions during Frame creation

      (Step 1 is only necessary in AWT as Swing is double buffered by default.)

    2. Always (important) call super() in your Frame.paint() implementation

    3. Set the background colour with setBackground() then the background should always be the same colour when expanding the frame

    Sample code:

        class InnerFrame extends Frame {
            public void addNotify() {
                super.addNotify();
                // Buffer
                createBufferStrategy(2);           
                strategy = getBufferStrategy();
            }
    
            public void paint(Graphics g) {
                super(g);
                //...
            }
            //...
         }
    

提交回复
热议问题