2012-08-09 41 views
0

我有一個背景顏色爲黑色的JFrame。如何設置剛性區域的顏色

setBackground(Color.BLACK); 

我用RigidArea作爲過濾:

Component rigidArea = Box.createRigidArea(new Dimension(0, 20)); 
rigidArea.setBackground(Color.BLACK); 
getContentPane().add(rigidArea); 

但是,這並不工作,因爲rigidArea的顏色不是黑色。這裏有什麼問題?

+0

['Box.createRigidArea'](http://docs.oracle.com/javase/7/docs/api/javax/swing/Box.html#createRigidArea(java.awt.Dimension中))表示非常簡單... *創建一個總是指定大小的不可見組件*。 – oldrinb 2012-08-09 20:08:12

回答

2

你試過Jframe的內容窗格的背景太設置爲黑色?

getContentPane().setBackground(Color.BLACK);

+0

嗯..它的作品。如果我直接使用'setBackground(Color.BLACK());'而不是'getContentPane()。setBackground(Color.BLACK);' – Cacheing 2012-08-09 20:09:49

+0

'setBackground(Color.BLACK());'它在哪裏設置背景顏色? – Cacheing 2012-08-09 20:10:34

+0

您不直接將小部件添加到「JFrame」中,而是將它們添加到其默認爲「JPanel」的contentPane。 – 2012-08-10 13:25:19

1

docs,createRigidArea創建一個總是指定大小的隱形組件。

對於有形成分,你可以創建一個輔助方法來創建一個JPanel:

JComponent createVisibleComponent(Dimension d) { 
    JPanel panel = new JPanel(); 
    panel.setMinimumSize(d); 
    panel.setMaximumSize(d); 
    panel.setPreferredSize(d); 

    return panel; 
} 
0

爲什麼不能簡單地增加一個JPanel並指定其尺寸是多少?

JPanel pan = new JPanel(); 
pan.setBackground(Color.BLACK); 
Dimension d = new Dimension(0,20); 
pan.setSize(d); 
pan.setPreferredSize(d); 
pan.setMaximumSize(d); 
pan.setMinimumSize(d); 
getContentPane().add(pan);