2011-11-02 73 views
3

我試圖讓一個按鈕有一個禁用文本的紅色和其他禁用文本的藍色,但使用下面的代碼時,它所做的只是使它們都爲紅色。爲兩個不同的JButton設置一個不同的禁用顏色? (UIManager.getDefaults更改這兩個按鈕)

有沒有簡單的方法來解決這個問題?

UIManager.getDefaults().put("Button.disabledText",Color.BLUE); 
button1.setEnabled(false); 
UIManager.getDefaults().put("Button.disabledText",Color.RED); 
button2.setEnabled(false); 

回答

0
/** 
* Sets the Color of the specified button. Sets the button text Color to the inverse of the Color. 
* 
* @param button The button to set the Color of. 
* @param color The color to set the button to. 
*/ 
private static void setButtonColor(JButton button, Color color) 
{ 
    // Sets the button to the specified Color. 
    button.setBackground(color); 
    // Sets the button text to the inverse of the button Color. 
    button.setForeground(new Color(color.getRGB()^Integer.MAX_VALUE)); 
} 

下面是一些代碼,我在

http://www.daniweb.com/software-development/java/threads/9791

希望它可以幫助發現!我真的不明白這個問題:P

+0

我試圖同時按鈕被禁用更改文本(button.setEnabled(假))。我相信你給我的代碼只會影響按鈕啓用時的顏色(button.setEnabled(true))。 – billyslp

2

外觀由ButtonUI決定,用戶選中Look &指定感覺。如果您要創建自己的L & F,則可以覆蓋getDisabledTextColor()。這個相關example可能會建議如何進行。雖然技術上可行,但我不確定用戶如何解釋這種差異。

雖然它與您的需求相切,但JTextComponent的後代爲此提供​​了setDisabledTextColor()

+1

*「雖然技術上可行,但我不確定用戶如何解釋這種差異。」*僅僅因爲我們擁有這項技術,並不意味着我們應該使用它。 –

+1

當前的JVM實例只有一個UIManager +1 – mKorbel

0

正如thrashgod所說,該按鈕的ButtonUI可控制禁用的文本顏色。幸運的是,你可以改變一個按鈕的ButtonUI

button1.setUI(new MetalButtonUI() { 
    protected Color getDisabledTextColor() { 
     return Color.BLUE; 
    } 
}); 
button1.setEnabled(false); 
button2.setUI(new MetalButtonUI() { 
    protected Color getDisabledTextColor() { 
     return Color.RED; 
    } 
}); 
button2.setEnabled(false); 
相關問題