JLabel的不是灰色的禁用后,当显示HTML文本
-
19-09-2019 - |
题
我如何获得JLabel
显示HTML字符串出现灰色的(这是不显示HTML文本JLabel
s的行为)?有另一种方式比通过修改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不支持自动变灰JLabel
s的,当他们使用HTML文本。 苏拉杰的解决方案已经到来最接近考虑的限制修复
我然而,尝试了不同的外的盒子的方法,其中,我已经把HTML文本JLabel
s内部的内JPanel
的和这样做:
mInnerPanel.setEnabled(shouldShow); //shouldShow is a boolean value
这没有奏效。对于这种方式的任何建议?
编辑:添加实施的解决方案。
解决方案
如果文本是HTML,文本不会被由于在BasicLabelUI#paint()
以下代码变灰
View v = (View) c.getClientProperty(BasicHTML.propertyKey);
if (v != null) {
v.paint(g, paintTextR);
}
正如你可以看到,如果文字是HTML,则使用查看油漆和wheter标签的启用与否未选中。 因此,我们需要显式地做到这一点,如下所示:
label2.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (!evt.getPropertyName().equals("enabled"))
return;
if (evt.getNewValue().equals(Boolean.FALSE))
label2.setText("<html><font color=gray>HTML <b>text</b></html>");
else
label2.setText("<html><font color=black>HTML <b>text</b></html>");
}
});
其他提示
实施的解决方案:
Color foreground = (shouldShow) ? SystemColor.textText : SystemColor.textInactiveText;
for (Component comp : mInnerPanel.getComponents())
{
comp.setForeground(foreground);
}
妥协了,用到底setForeground
,因为它看起来似乎是Java的绘画enabled
s时,只要它包含HTML文本明确地忽略JLabel
财产。另请参见 @苏拉杰的回答,对于 “纯” 的解决方案。
我建议以下内容,这是这里所提供两种解决方案的组合:
public class HtmlLabel extends JLabel{
public void setEnabled(boolean enabled){
if(getClientProperty(BasicHTML.propertyKey) != null ){
Color foreground = (enabled) ? SystemColor.textText : SystemColor.textInactiveText;
setForeground(foreground);
}
super.setEnabled(enabled);
}
}
您可以指定在HTML的字体颜色。
覆盖在UI paint方法,被设置为空值的客户端属性的 BasicHTML.propertyKey 如果它被禁止并调用super ...
不隶属于 StackOverflow