這裏是自定義渲染器的代碼:當有在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
,問題是爲什麼它的行爲這種方式(功能),如果沒有的元素,我希望它不會被稱爲,但它爲什麼被稱爲?畢竟,如果沒有元素,它是什麼格式。
更新:可以使用以下接受的答案。至於爲什麼它的行爲如此,這是因爲列表必須有一個空字符串;您知道第一次初始化組合框時默認選中的空字符串。
1)爲了更快得到更好的幫助,請發佈[SSCCE](http://sscce.org/)。 2)始終複製/粘貼錯誤和異常輸出。 –
向下轉換是危險的,請使用'instanceof' – nachokk
永遠不要爲XxxRenderer內部的轉換組件設置值 – mKorbel