2010-02-11 45 views
9

如何獲取顯示HTML字符串的JLabel灰顯(這是不顯示HTML文本的行爲JLabel)?通過修改​​屬性,是否有另一種方法實際上改變顏色?JLabel在禁用時不會變灰,當顯示HTML文本時

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's solution已經接近該修復。

我已經然而,嘗試了不同外的的盒的方法,我已經把HTML文本JLabel的內線內JPanel,並且這樣做:

mInnerPanel.setEnabled(shouldShow); //shouldShow is a boolean value 

尚未奏效。對此有何建議?


編輯:添加implemented solution

+0

你應該修改你原來的問題沒有發佈另一個 – Lombo 2010-02-11 05:49:58

+0

@Lombo,是我不好,我不知道 - 刪除前一個。 – bguiz 2010-02-11 05:59:49

+0

這似乎在Java 1.7中得到修復。 – SystemParadox 2013-12-05 09:18:26

回答

10

如果文本是HTML,文字不會被在BasicLabelUI#paint()

 View v = (View) c.getClientProperty(BasicHTML.propertyKey); 
     if (v != null) { 
     v.paint(g, paintTextR); 
     } 

變灰,因爲下面的代碼正如你可以看到,如果文字是HTML,則使用查看油漆,它不是檢查標籤是否啓用。 因此,我們需要顯式地做到這一點,如下圖所示:

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>"); 
    } 
    }); 
+1

'setForeground'的作品,所以我建議使用它而不是改變標籤文字來改變顏色。 – lins314159 2010-02-11 06:11:37

+0

儘管就我而言,更改HTML可能不是一種好的做法。 – user12458 2013-07-12 05:18:43

0

您可以在HTML中指定字體顏色。

+0

@camickr:所以每當啓用/禁用狀態改變時,我都必須這樣做。 – bguiz 2010-02-11 06:01:01

+0

是的,這就是爲什麼使用setForeground()方法仍然是最簡單的解決方案。 – camickr 2010-02-11 15:50:36

0

覆蓋在UI paint方法,設置客戶端屬性BasicHTML.propertyKey爲null,如果它被禁用,並調用超...

+1

@sreejith ...顯然它不會工作,原因有兩個:a)如果你設置了BasicHTML。propertyKey爲null,則使用html呈現的任何組件將無法繪製html b)儘管文本將以灰色顯示,但它將顯示entrie html,即它將顯示「 HTML text」而不是HTML文本。 :) – 2010-02-11 08:57:53

4

實施的解決方案:

Color foreground = (shouldShow) ? SystemColor.textText : SystemColor.textInactiveText; 
    for (Component comp : mInnerPanel.getComponents()) 
    { 
     comp.setForeground(foreground); 
    } 

妥協了,用到底setForeground,因爲它似乎是Java的似乎當p明確忽略enabled財產只要它包含HTML文本,就可以使用JLabel。對於「純」解決方案,另見@Suraj's answer

2

我建議以下,這是在這裏提供兩種解決方案的組合:

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); 
    } 
} 
相關問題