简体   繁体   English

ListCellRenderer强制转换异常

[英]ListCellRenderer casting exception

Here is the code of the custom renderer: 以下是自定义渲染器的代码:

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;
    }

}

Everything works fine except when there are no items in the DefaultComboBoxModel , in which case getListCellRendererComponent is called with String value of "" , which causes the error as it expects a Facility object instead. 除非DefaultComboBoxModel中没有项目,否则一切正常,在这种情况下,使用String""调用getListCellRendererComponent ,这会导致错误,因为它需要Facility对象。

Why does it behave this way? 为什么它会这样?

Update : I know that the error is because of the casting and I know how to use instance of , the question is why it behaves this way (the function), if there are no elements, I would expect it not to be called at all, but why it is called? 更新 :我知道错误是由于转换而我知道如何使用instance of ,问题是为什么它的行为方式(函数),如果没有元素,我会期望它根本不被调用,但为什么叫它? After all, what does it format if there are no elements. 毕竟,如果没有元素,它会格式化什么。

Update : The accepted answer below can be used. 更新 :可以使用下面接受的答案。 As for why it behaves so, it is because the list has to have an empty string; 至于为什么它表现如此,这是因为列表必须有一个空字符串; you know the empty string that is selected by default when initializing the combobox for the first time. 你知道第一次初始化组合框时默认选择的空字符串。

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;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM