有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

}

除了在DefaultComboBoxModel中没有任何项外,其他一切都正常工作,在这种情况下,使用String""调用getListCellRendererComponent,这会导致错误,因为它需要一个Facility对象

为什么会这样

更新:我知道错误是由于强制转换引起的,我知道如何使用instance of,问题是它为什么会这样(函数),如果没有元素,我希望它根本不会被调用,但为什么会被调用?毕竟,如果没有元素,它的格式是什么

更新:可以使用下面接受的答案。至于它为什么这样做,是因为列表必须有一个空字符串;您知道第一次初始化组合框时默认选择的空字符串


共 (1) 个答案

  1. # 1 楼答案

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