當前位置:編程學習大全網 - 腳本源碼 - java窗口背景顏色怎麽設定?用setBackground()好像不行,請大俠指教!

java窗口背景顏色怎麽設定?用setBackground()好像不行,請大俠指教!

妳好!

首先,妳說的Java窗口是指JFrame或者Frame

其次,妳說的窗口背景顏色是指直接調用JFrame或者Frame的setBackground(Color?color)方法設置後顯示出來的顏色。其實,妳的想法是正確的,但是我想提醒妳的是,妳沒搞明白JFrame的顯示機制。在妳直接調用這個方法後,妳的確設置了背景顏色,而妳看到的卻不是直接的JFrame或者Frame,而是JFrame.getContentPane().而JFrame上的contentPane默認是Color.WHITE的,所以,無論妳對JFrame或者Frame怎麽設置背景顏色,妳看到的都只是contentPane.

最後,講解決辦法:

辦法A:在完成初始化,調用getContentPane()方法得到壹個contentPane容器,然後將其設置為不可見,即setVisible(false)。這樣,妳就可以看到JFrame的廬山真面貌啦!

核心代碼this.getContentPane().setVisible(false);//得到contentPane容器,設置為不可見

實例完整代碼如下:

/*

*?TestJFrameBGColor.java

*

*?Created?on?2011-5-8,?0:21:20

*/

package?testjframebgcolor;

import?java.awt.Color;

/**

*

*?@author?葉科良

*/

public?class?TestJFrameBGColor?extends?javax.swing.JFrame?{

/**?Creates?new?form?TestJFrameBGColor?*/

public?TestJFrameBGColor()?{

initComponents();

this.getContentPane().setVisible(false);//得到contentPane容器,設置為不可見

}

/**?This?method?is?called?from?within?the?constructor?to

*?initialize?the?form.

*?WARNING:?Do?NOT?modify?this?code.?The?content?of?this?method?is

*?always?regenerated?by?the?Form?Editor.

*/

@SuppressWarnings("unchecked")

//?<editor-fold?defaultstate="collapsed"?desc="Generated?Code">

private?void?initComponents()?{

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

org.jdesktop.application.ResourceMap?resourceMap?=?org.jdesktop.application.Application.getInstance(testjframebgcolor.TestJFrameBGColorApp.class).getContext().getResourceMap(TestJFrameBGColor.class);

setBackground(resourceMap.getColor("Form.background"));?//?NOI18N

setName("Form");?//?NOI18N

javax.swing.GroupLayout?layout?=?new?javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGap(0,?400,?Short.MAX_VALUE)

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGap(0,?300,?Short.MAX_VALUE)

);

pack();

}//?</editor-fold>

/**

*?@param?args?the?command?line?arguments

*/

public?static?void?main(String?args[])?{

java.awt.EventQueue.invokeLater(new?Runnable()?{

public?void?run()?{

new?TestJFrameBGColor().setVisible(true);

}

});

}

//?Variables?declaration?-?do?not?modify

//?End?of?variables?declaration

}

方法B:將contentPane的顏色設置為妳想要的顏色,而不是對JFrame本身設置,

核心代碼:this.getContentPane().setBackground(Color.red);//設置contentPane為紅色

將核心代碼替換方法A核心代碼即可實現

方法C:為JFrame添加壹個Panel或者JLabel等其他組件,設置其顏色為妳想要的顏色,然後將其覆蓋JFrame窗口即可

  • 上一篇:風水書裏的門樓是什麽意思
  • 下一篇:c語言程序,如何實現把本身程序刪除。如打開1.exe,然後1.exe的功能就是刪除本身,運行結束後
  • copyright 2024編程學習大全網