setBackground(Color.red)
JPanel使用可以改变颜色,而像JFrame、JContentPane使用却改变不了,这是为什么?

解决方案 »

  1.   

    有时在JFrame里面添加JPanel或其他组件是。就把JFrame给盖住了。。所以这时修改其背景颜色就没用了。。
      

  2.   

    还是给代码吧
    import java.awt.*;
    import javax.swing.*;public class Test {
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = (JPanel)frame.getContentPane();
    panel.setOpaque(true);
    panel.setBackground(Color.RED);
    frame.setSize(100, 100);
    frame.setVisible(true);
    }
    }
      

  3.   

    不好意思看错了
    最近老犯晕
    JFrame包含很多pane
    从上往下
    glasspane
    contentpane
    layeredpane
    rootpane
    看下代码import java.awt.*;
    import javax.swing.*;public class Test {
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    Component p = frame.getGlassPane();
    Container pp = frame.getContentPane();
    JLayeredPane ppp = frame.getLayeredPane();
    JRootPane pppp = frame.getRootPane();
    //((JComponent)pp).setOpaque(false); //1
    //pppp.setOpaque(false); //2
    p.setBackground(Color.YELLOW);
    pp.setBackground(Color.BLACK);
    ppp.setBackground(Color.GREEN);
    pppp.setBackground(Color.BLUE);
    frame.setBackground(Color.RED);
    frame.setSize(100, 100);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    }
    }运行结果显示的是黑色,这是因为glasspane是透明的,contentpane不透明
    将一句的注释去掉,让contentpane透明,这时候看到的颜色是蓝色
    因为layeredpane透明,rootpane不透明将2句的注释也去掉,让rootpane透明,并没有得到期望的红色
    而是白色,好像还有至少一层东西在frame之上
    至于这个是什么,看了会源码也没找到
    希望高手解答
      

  4.   

    那为什么frame可以呢……而JFrame不可以^