为两个不同的JButton设置一个不同的禁用颜色? (UIManager.getDefaults更改这两个按钮)

为两个不同的JButton设置一个不同的禁用颜色? (UIManager.getDefaults更改这两个按钮)

问题描述:

我试图让一个按钮有一个禁用文本的红色和其他禁用文本的蓝色,但使用下面的代码时,它所做的只是使它们都为红色。为两个不同的JButton设置一个不同的禁用颜色? (UIManager.getDefaults更改这两个按钮)

有没有简单的方法来解决这个问题?

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

/** 
* 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

外观由ButtonUI决定,用户选中Look &指定感觉。如果您要创建自己的L & F,则可以覆盖getDisabledTextColor()。这个相关example可能会建议如何进行。虽然技术上可行,但我不确定用户如何解释这种差异。

虽然它与您的需求相切,但JTextComponent的后代为此提供​​了setDisabledTextColor()

+1

*“虽然技术上可行,但我不确定用户如何解释这种差异。”*仅仅因为我们拥有这项技术,并不意味着我们应该使用它。 –

+1

当前的JVM实例只有一个UIManager +1 – mKorbel

正如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);