当显示 HTML 文本时,JLabel 禁用时不会变灰
如何让显示 HTML 字符串的 JLabel
显示为灰色(这是不显示 HTML 文本的 JLabel
的行为)?除了通过修改 foreground
属性来实际更改颜色之外,还有其他方法吗?
JLabel label1 = new JLabel("Normal text");
JLabel label2 = new JLabel("<html>HTML <b>text</b>");
// Both labels are now black in colour
label1.setEnabled(false);
label2.setEnabled(false);
// label1 is greyed out, label2 is still black in colour
非常感谢您的所有回复。据我所知,Java 似乎不支持在使用 HTML 文本时自动变灰 JLabel
。 Suraj 的解决方案来了考虑到限制,最接近修复。
然而,我尝试了一种不同的开箱即用方法,我将 HTML 文本 JLabel
放在内部 JPanel
中,并执行了以下操作
mInnerPanel.setEnabled(shouldShow); //shouldShow is a boolean value
:成功了。对于这种方式有什么建议吗?
编辑:添加了已实现的解决方案。
How do I get a JLabel
displaying a HTML string to appear greyed out (which is the behaviour of JLabel
s that don't display HTML text)? Is there another way than actually changing the colour myself by modifying the foreground
property?
JLabel label1 = new JLabel("Normal text");
JLabel label2 = new JLabel("<html>HTML <b>text</b>");
// Both labels are now black in colour
label1.setEnabled(false);
label2.setEnabled(false);
// label1 is greyed out, label2 is still black in colour
Thank you very much for all of your responses. From what I gather, it seems that Java doesn't support automatic greying out of JLabel
s when they use HTML text. Suraj's solution has come closest to the fix considering the limitations.
I have however, tried a different out-of-the box approach, where I have put the HTML text JLabel
s inside of an inner JPanel
and did this:
mInnerPanel.setEnabled(shouldShow); //shouldShow is a boolean value
Which hasn't worked. Any suggestions for this way?
EDIT: Added implemented solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果文本是 HTML,则文本不会变灰,因为
BasicLabelUI#paint()
中的以下代码如您所见,如果文本是 html,则 View 用于绘制,而它不是检查标签是否启用。
因此我们需要明确地这样做,如下所示:
If text is HTML, the text wont be grayed out because of the following code in
BasicLabelUI#paint()
As you can see if the text is html, then the View is used to paint and it is not checked wheter the label is enabled or not.
Hence we need to do it explictly as shown below:
实现的解决方案:
最终陷入并使用了
setForeground
,因为看起来Java在绘制JLabel
时似乎显式忽略了enabled
属性,所以只要它包含 HTML 文本。另请参阅@Suraj 的回答,用于“纯”解决方案。Implemented solution:
Caved in and used
setForeground
in the end, as it appears that Java seems to explicitly ignore theenabled
property when paintingJLabel
s so long as it contains HTML text. See also @Suraj's answer, for "pure" solution.我建议如下,它是此处提供的两种解决方案的组合:
I would suggest the following, which is combination of two solutions provided here:
您可以在 HTML 中指定字体颜色。
You can specify the font color in the HTML.
重写 UI 中的绘制方法,将客户端属性 BasicHTML.propertyKey 设置为 null(如果禁用)并调用 super...
Override the paint method in the UI, set the client property BasicHTML.propertyKey to null if it is disabled and call super...