以下是自定义呈现器的代码:
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,问题是为什么它以这种方式运行(函数),如果没有元素,我希望它不会被调用,而是为什么会被调用?毕竟,如果没有元素,它的格式是什么?
更新:可以使用下面接受的答案。至于为什么会这样做,这是因为列表必须有一个空字符串;您知道默认情况下第一次初始化组合框时选择的空字符串。
发布于 2013-07-10 14:37:34
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;
}
}https://stackoverflow.com/questions/17573251
复制相似问题