Java基础——解决JFrame.setBackground设置无效,mac系统IDEA编译器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Katherine_java/article/details/81987362

原理:

JFrame框架,一旦创建,在其中就已经包含一个内容面板。
一般我们在往JFrame中添加组件时,都加在了内容面板中,这个面板可以通过JFrame的成员方法getContentPane()取出来,所以如果设置JFrame的背景颜色,仍然会被内容面板盖住,不如设置内容面板的背景颜色,如果框架中还加有其他面板,内容面板的颜色也会被其他面板盖住,要注意一下面板的布局情况。

设置方法:

方法1:得到contentPane容器,设置为不可见;否则背景颜色被遮挡,setBackground()失效
jf.getContentPane().setVisible(false);
jf.setBackground(Color.BLACK);

方法2:直接设置contentPane容器,设置颜色
jf.getContentPane().setBackground(Color.BLACK);

例子:

    private void showUI() {
        JFrame jf = new JFrame();
        jf.setName("线程小球V1");
        jf.setSize(500,500);
        jf.setLocationRelativeTo(null);
        jf.setDefaultCloseOperation(3);

        //方法1:得到contentPane容器,设置为不可见;否则背景颜色被遮挡,setBackground()失效
        jf.getContentPane().setVisible(false);
        jf.setBackground(Color.BLACK);
        
        //方法2:直接设置contentPane容器,设置颜色
        jf.getContentPane().setBackground(Color.BLACK);

        jf.setVisible(true);

    }

猜你喜欢

转载自blog.csdn.net/Katherine_java/article/details/81987362