最近一些學習Java的小伙伴,向我請教了一些關於Java圖形化界面的問題,以下就是我對Java圖形化界面的一些總結。 一:為何J Frame無法顯示添加的顏色 public class Login extends JFrame{ public Login(){ this.setLayout(null ...
最近一些學習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();
}
}
添加改變後的效果圖: