这是自定义渲染器的代码:
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
相反,对象。
为什么会这样?
更新:我知道错误是由于转换造成的,并且我知道如何使用 instance of
,问题是为什么它会这样(函数),如果没有元素,我希望它根本不会被调用,但为什么会调用它?毕竟,如果没有元素,它会格式化什么。
更新:可以使用下面接受的答案。至于为什么会这样,是因为列表必须有一个空字符串;您知道第一次初始化组合框时默认选择的空字符串。
最佳答案
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;
}
}
关于java - ListCellRenderer 转换异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17573251/