如何在 Java 中更改禁用的 JButton 的外观

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1590764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:12:04  来源:igfitidea点击:

How to change the look of a disabled JButton in java

javacolorsjbutton

提问by Patrick

I am making a game and when I disable a button with setEnabled(false);the buttons turns grey which clashes with the other colors in the game. Is their a way to change the color of the button when it is disabled?

我正在制作一个游戏,当我禁用一个按钮时 setEnabled(false);,按钮变成灰色,与游戏中的其他颜色发生冲突。他们是一种在禁用按钮时更改按钮颜色的方法吗?

回答by user929404

You can add HTML coding to your button which gives a large range of flexibility, even to disabled buttons.

您可以向按钮添加 HTML 编码,这提供了很大的灵活性,甚至是禁用的按钮。

Example: button.setText("<html><font color = red>3</font></html>");

回答by Arne

Calling setContentAreaFilled(false)on a button will make a button look as if it is disabled, even if it is not. It doesn't, however, seem to work the other way around.

在按钮上调用setContentAreaFilled(false)将使按钮看起来好像被禁用,即使它不是。然而,它似乎并没有反过来工作。

If you don't need your button to look enabled, then it is a nice fix.

如果您不需要按钮看起来已启用,那么这是一个不错的解决方案。

Docs Oracle

文档 Oracle

回答by camickr

If you are talking about the text, then you might be able to use the UIManager to change the disabled foreground color. Check out the UIManager Defaults.

如果您正在谈论文本,那么您也许可以使用 UIManager 来更改禁用的前景色。查看UIManager Defaults

回答by Mangara

The button's ButtonUIcontrols the disabled text color. Luckily, you can change it:

该按钮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);

回答by Nick Veys

You'll want to modify the Look and Feelyou are using. There are tons available for download and you can of course make your own.

您需要修改正在使用的外观。有大量可供下载,您当然可以自己制作。

回答by OscarRyz

You can also set a disable icon with JButton.setDisableIcon()

您还可以使用JButton.setDisableIcon()设置禁用图标

回答by clamp

i am not 100% on this, but i think you can overwrite the paint method of the button's glasspane to overlay it with the color of your choice.

我不是 100% 对此,但我认为您可以覆盖按钮玻璃窗格的绘制方法,以将其覆盖为您选择的颜色。

here is a tutorial on the panes of a container:

这是有关容器窗格的教程:

http://java.sun.com/docs/books/tutorial/uiswing/components/rootpane.html

http://java.sun.com/docs/books/tutorial/uiswing/components/rootpane.html