Java基礎——解決JFrame.setBackground設定無效,mac系統IDEA編譯器
阿新 • • 發佈:2018-12-05
原理:
JFrame框架,一旦建立,在其中就已經包含一個內容面板。
一般我們在往JFrame中新增元件時,都加在了內容面板中,這個面板可以通過JFrame的成員方法getContentPane()取出來,所以如果設定JFrame的背景顏色,仍然會被內容面板蓋住,不如設定內容面板的背景顏色,如果框架中還加有其他面板,內容面板的顏色也會被其他面板蓋住,要注意一下面板的佈局情況。
設定方法:
方法1:得到contentPane容器,設定為不可見;否則背景顏色被遮擋,setBackground()失效 jf.getContentPane().setVisible(false); jf.setBackground(Color.BLACK); 方法2:直接設定contentPane容器,設定顏色 jf.getContentPane().setBackground(Color.BLACK);
例子:
private void showUI() { JFrame jf = new JFrame(); jf.setName("執行緒小球V1"); jf.setSize(500,500); jf.setLocationRelativeTo(null); jf.setDefaultCloseOperation(3); //方法1:得到contentPane容器,設定為不可見;否則背景顏色被遮擋,setBackground()失效 jf.getContentPane().setVisible(false); jf.setBackground(Color.BLACK); //方法2:直接設定contentPane容器,設定顏色 jf.getContentPane().setBackground(Color.BLACK); jf.setVisible(true); }