java窗口背景顏色的設定----setBackground()的用法

窗口背景顏色是指直接調用JFrame或者Frame的setBackground(Color color)方法設置後顯示出來的顏色。如果直接調用這個方法後,的確設置了背景顏色,但看到的卻不是直接的JFrame或者Frame,而是JFrame.getContentPane(),而JFrame上的contentPane默認是Color.WHITE的,所以,無論你對JFrame或者Frame怎麼設置背景顏色,你看到的都只是contentPane.

解決方法

辦法A:在完成初始化,調用getContentPane()方法得到一個contentPane容器,然後將其設置爲不可見,即setVisible(false)。

import javax.swing.*;
import java.awt.*
public class TestMenuBar1 {
	public static void main(String arg[]) {
		createNewMenu ck=new createNewMenu("第一個窗口");
	}
}
class createNewMenu extends JFrame{
	public createNewMenu(String title) {
		getContentPane().setVisible(false);
		setBackground(Color.blue);  //設置窗口背景顏色
		setTitle(title);
		setBounds(200,200,500,500); //設置窗口位置和大小
		setVisible(true);  //設置窗口可見
	}
}

辦法B:直接加 this.getContentPane().setBackground(Color.blue);

import java.awt.*;
import javax.swing.*;
public class TestMenuBar1 {
	public static void main(String arg[]) {
		createNewMenu ck=new createNewMenu("第一個窗口");
	}
}
class createNewMenu extends JFrame{
	public createNewMenu(String title) {
		setTitle(title);
		setBounds(200,200,500,500);
		setVisible(true);
		this.getContentPane().setBackground(Color.blue);
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章