Disabling individual JComboBox items

This is a fairly common problem, and the solution I used is similar to what I was looking for and found it later. One implements ListCellRendererc JLabel, which enables or disables itself based on the currently selected index:

public Component getListCellRendererComponent(JList list, Object value,
        int index, boolean isSelected, boolean cellHasFocus) {
    setText(value.toString());
    UIDefaults defaults = UIManager.getDefaults();
    Color fc;
    if (index == 1) {
        setEnabled(false);
        fc = defaults.getColor("Label.disabledForeground");
        setFocusable(false);
    } else {
        // fc = defaults.getColor("Label.foreground");
        fc = list.getForeground();
        setEnabled(list.isEnabled());
        setFocusable(true);
    }
    setForeground(fc);
    setBackground(isSelected ? list.getSelectionBackground() : list
            .getBackground());
    return this;
}

The problem is that although the list item is visually displayed as disabled, you can select it despite the call setFocusable. How can i turn it off?

+4
source share
1 answer

You need to somehow deny ComboBoxthe ability to set items that cannot be selected from the selected ones.

The easiest way I can come up with is to catch the change in choice in the model itself.

public class MyComboBoxModel extends DefaultComboBoxModel {

    public MyComboBoxModel() {

        addElement("Select me");
        addElement("I can be selected");
        addElement("Leave me alone");
        addElement("Hit me!!");

    }

    @Override
    public void setSelectedItem(Object anObject) {

        if (anObject != null) {

            if (!anObject.toString().equals("Leave me alone")) {

                super.setSelectedItem(anObject);

            }

        } else {

            super.setSelectedItem(anObject);

        }

    }

}

, . , items . , , - item, isSelectable.

ComboBoxModel, , items, model.contains(item) , , .

+3

All Articles