2013-07-10 47 views
0

這裏是自定義渲染器的代碼:當有在DefaultComboBoxModel沒有項目,在這種情況下getListCellRendererComponent被調用的""String值,這將導致除ListCellRenderer鑄造例外

private class FacilityElement extends javax.swing.JLabel implements javax.swing.ListCellRenderer { 

    @Override 
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { 
     if(isSelected) { 
      setBackground(list.getSelectionBackground()); 
      setForeground(list.getSelectionForeground()); 
     } 
     else { 
      setBackground(list.getBackground()); 
      setForeground(list.getForeground()); 
     } 
     setFont(list.getFont()); 
     setText(" " + ((Facility) value).getName()); // The error is here 
     setOpaque(true); 

     return this; 
    } 

} 

一切正常錯誤,因爲它預期Facility對象。

它爲什麼會這樣?

更新:我知道錯誤是由於鑄造的,我知道如何使用instance of,問題是爲什麼它的行爲這種方式(功能),如果沒有的元素,我希望它不會被稱爲,但它爲什麼被稱爲?畢竟,如果沒有元素,它是什麼格式。

更新:可以使用以下接受的答案。至於爲什麼它的行爲如此,這是因爲列表必須有一個空字符串;您知道第一次初始化組合框時默認選中的空字符串。

+0

1)爲了更快得到更好的幫助,請發佈[SSCCE](http://sscce.org/)。 2)始終複製/粘貼錯誤和異常輸出。 –

+0

向下轉換是危險的,請使用'instanceof' – nachokk

+0

永遠不要爲XxxRenderer內部的轉換組件設置值 – mKorbel

回答

2
private class FacilityElement extends javax.swing.JLabel implements javax.swing.ListCellRenderer { 

    @Override 
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { 
     if(isSelected) { 
      setBackground(list.getSelectionBackground()); 
      setForeground(list.getSelectionForeground()); 
     } 
     else { 
      setBackground(list.getBackground()); 
      setForeground(list.getForeground()); 
     } 
     setFont(list.getFont()); 
     if (value instanceof Facility) { // Try this 
      setText(" " + ((Facility) value).getName()); 
     }  
     setOpaque(true); 

     return this; 
    } 

} 
+0

請使用代碼格式用於代碼,輸入/輸出和結構化文檔,如HTML或XML。爲此,請選擇樣本並單擊郵件發佈/編輯表單上方的「{}」按鈕。 –