简体   繁体   中英

Disabling individual JComboBox items

This is a fairly common problem, and the solution I've used is similar to what I searched and found later. One implements a ListCellRenderer with a JLabel that enables or disables itself based on the current 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 even though visually the list item shows up as disabled, it can still be selected despite the setFocusable call. How do I actually disable it?

You need some way to discourage the ComboBox from been able to set the item(s) that can't be selected from been selected.

The easiest way I can think of is to trap the change in the selection within 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);

        }

    }

}

Now this is a quick hack to prove the point. What you really need is someway to mark certain items as unselectable. The easiest way I can think of is to provide a property in the item , such as isSelectable for example.

Failing that, you could construct a special ComboBoxModel that maintain a separate inner model that contained a reference to all the unselectable items , so that a quick model.contains(item) could be used to determine if the item is selectable or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM