2014-11-04 126 views
-1

這實際上是我的代碼。JButton.setBackground函數無法正常工作

JButton but = new JButton("="); 
but.setOpaque(true); 
if (but.getText() == "=") 
{ 
    but.setForeground(Color.WHITE); 
    but.setBackground(Color.BLUE); 
    but.addActionListener(listen); 
    but.setPreferredSize(new Dimension(30, 30)); 
    numberZone.add(but); 
} 

setForeground功能,但不是setBackground。 我嘗試setOpaque函數,但沒有任何更改。 我在一個mac OSX系統上。我不知道這是否重要。

感謝和抱歉我的英語錯誤。

回答

2

警告!!!

切勿使用==因爲==比較,如果一個對象引用是一樣的另一個東西,你不感興趣在大多數情況下比較字符串。在比較字符串時,您通常想知道兩個字符串是否具有相同順序的相同字符。所以使用if (string1.equals(string2))if string1.equalsIgnoreCase(string2))

您還正在檢查字符串的文本,看起來不是ActionListener中的創建代碼或其他一些事件觸發的代碼,這些代碼會讓我感到困惑。

在這裏,你會怎麼做

// in your ActionListener 
public actionPerformed(ActionEvent e) { 
    if ("=".equals(e.getActionCommand())) { 
     // here your Strings are == 
    } 
} 
+0

你是對的大約相等的功能。我嘗試過,但setBackground函數總是不起作用。 – gillioa 2014-11-05 00:04:01

+0

@gillioa:顯示更多代碼和背景信息。最好的代碼是[mcve](http://stackoverflow.com/help/mcve)。 – 2014-11-05 00:16:17