首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ListCellRenderer铸造异常

ListCellRenderer铸造异常
EN

Stack Overflow用户
提问于 2013-07-10 14:26:14
回答 1查看 131关注 0票数 0

以下是自定义呈现器的代码:

代码语言:javascript
复制
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中没有项时,一切都运行良好,在这种情况下,getListCellRendererComponent是用""String值调用的,这会导致错误,因为它需要一个Facility对象。

它为什么会这样表现?

Update:我知道错误是因为转换,我知道如何使用instance of,问题是为什么它以这种方式运行(函数),如果没有元素,我希望它不会被调用,而是为什么会被调用?毕竟,如果没有元素,它的格式是什么?

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-10 14:37:34

代码语言:javascript
复制
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;
    }

}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17573251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档