如何为Java中的窗口(JFrame)添加颜色

最近一些学习Java的小伙伴,向我请教了一些关于Java图形化界面的问题,以下就是我对Java图形化界面的一些总结。
一:为何J Frame无法显示添加的颜色

public class Login extends JFrame{
public Login(){
this.setLayout(null);
this.setBounds(600, 200, 200, 300);
this.setVisible(true);
this.setBackground(Color.yellow); //为窗体设置颜色
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
    new Login();
}

}
效果图:

为何会出现这样的问题呢?
其实是因为,JFrame在你直接调用这个方法后,你的确设置了背景颜色,而你看到的却不是直接的JFrame或者Frame,而是JFrame.getContentPane().而JFrame上的contentPane默认是Color.WHITE(白色)的,所以,无论你对JFrame或者Frame怎么设置背景颜色,你看到的都只是contentPane.不能够显示出你所设置的颜色(可以去了解一下图形化界面的知识)
解决这个问题的办法:
(1)在完成初始化,调用getContentPane()方法得到一个contentPane容器,然后将其设置为不可见,即setVisible(false)。这样,你就可以看到真正的JFrame了。
最重要的上代码:this.getContentPane().setVisible(false);//得到contentPane容器,设置为不可见
(2)既让默认是白色,那就直接改变contentPane的颜色就行了嘛,不直接对JFrame进行操作。
话不多说上代码:this.getContentPane().setBackground(Color.yellow);//设置contentPane为黄色
(3)最最常用的方法就是直接给JFrame添加一个JLabel(标签)或者JPanel(面板),直接设置面板或者标签的颜色就行了嘛。
话不多来个例子:
public class Login extends JFrame{
JPanel pan;
public Login(){
this.setLayout(null);
this.setBounds(400, 200, 400, 500);
this.setVisible(true);
this.setBackground(Color.yellow);
init();

}
public void init() {
    pan = new JPanel();
    pan.setLayout(null);
    pan.setVisible(true);
    pan.setBounds(0,0,400,500);
    pan.setBackground(Color.red);
    this.add(pan);
    
} 
public static void main(String[] args) {
    new Login();
}

}
添加改变后的效果图:

猜你喜欢

转载自www.cnblogs.com/lsy-zx/p/9446337.html