关于GUI编程设置框架颜色的一些问题

1.

class MyFrame extends JFrame
{
    public MyFrame()
    {
        ...
        this.setVisible(true);
        this.getContentpane().setVisible(true);
        ...
    }
}

代码中 this.setVisible(true) 用来控制框架窗口的可见性

this.getContentpane().setVisible(true) 用来控制内容窗格的可见性(默认为可见)

其中,内容窗格位于框架窗口之上(内容窗格覆盖框架窗格)

2.

由1可知,若想要设置背景颜色,有两种方式:

(1) 直接设置框架窗口的颜色

this.getContentpane().setVisible(false); //使内容窗口隐藏(透明化) 从而露出框架窗口
this.setBackground(Color.PINK);

此时由于内容窗口隐藏导致加入内容窗口中的组件随之隐藏(只能显示一个背景色),故此方法并不可取(没有卵用)

(2) 为加入到内容窗口的组件设置背景颜色

public MyFrame extends JFrame
{
    public MyFrame()
    {
        ...
        this.add(new canvas());
    }
}

class canvas extends JPanel
{
    public void paintComponent(Graphics g)
    {
        ...
        this.setBackground(Color.PINK); //对组件设置背景颜色
    }
}

此时由于组件位于内容窗口之上,而内容窗口默认可见,故背景颜色可以显示且组件内的信息也可显示.

你可能感兴趣的:(Java)