2010-11-13 152 views
11

下面是在特定的pannel3上以網格佈局形式創建9個按鈕的代碼。我想要的是讓每個按鈕的背景都以灰色文字覆蓋黑色。 任何人都可以幫忙嗎?如何在Java GUI中設置按鈕的背景顏色?

for(int i=1;i<=9;i++) 
{ 
    p3.add(new JButton(""+i)); 
} 
+5

老實說,人,使用IDE。自動完成是學習語言庫的最佳方法之一,方法名稱通常是不言自明的。 – 2010-11-14 04:36:01

+0

@DenisTulskiy爲什麼你的評論是必要的? – Ungeheuer 2015-06-02 02:55:24

+0

@JohnnyCoder,我想我很沮喪,這是我說rtfm的方式。我仍然認爲這是一個很好的建議,儘管:) – 2015-06-02 04:29:26

回答

16

檢查出JButton文檔。請特別注意從JComponent繼承的setBackgroundsetForeground方法。

喜歡的東西:

for(int i=1;i<=9;i++) 
{ 
    JButton btn = new JButton(String.valueOf(i)); 
    btn.setBackground(Color.BLACK); 
    btn.setForeground(Color.GRAY); 
    p3.add(btn); 
} 
+8

這不適用於Mac上的Java 8。背景顏色是按鈕背後的顏色。該按鈕然後被繪製在黑色背景的頂部,並且該按鈕是灰色並帶有灰色文本。 (你不能閱讀文本)。事實上,更糟糕的是,除非先調用setOpaque(true)',否則黑色背景根本不會被繪製。 – Jason 2016-03-10 23:25:46

3
for(int i=1;i<=9;i++) { 
    p3.add(new JButton(""+i) {{ 
     // initialize the JButton directly 
     setBackground(Color.BLACK); 
     setForeground(Color.GRAY); 
    }}); 
} 
1

使用setBackground方法來設置背景和setForeground改變文本的顏色。但請注意,將灰色文本置於黑色背景中可能會使您的文本難以閱讀。

2

您可能或可能不必使用setOpaque方法,以確保通過傳遞true方法顯示顏色。

0

看來,setBackground()方法在某些平臺(我正在使用Windows 7)上無法正常工作。我發現this answerthis question有幫助。但是,我並沒有完全用它來解決我的問題。相反,我認爲將按鈕旁邊的面板着色要容易得多,而且幾乎是美觀的。

11

簡單:

btn.setBackground(Color.red);

要使用RGB值:

btn[i].setBackground(Color.RGBtoHSB(int, int, int, float[]));

+1

我喜歡用btn.setBackground(New Color(int,int,int));爲RGB值 – 2016-01-26 02:02:28

1

更改背景屬性可能沒有足夠的組件將不會看起來像一個按鈕了。您可能需要重新實現paint方法,如here以獲得更好的結果:

enter image description here