2013-07-10 50 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。为此,请选择样本并单击邮件发布/编辑表单上方的“{}”按钮。 –