Question

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.

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? 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.

Was it helpful?

Solution

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

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top