Disabling individual JComboBox items

倾然丶 夕夏残阳落幕 提交于 2019-12-04 01:37:04

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/11895822/disabling-individual-jcombobox-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!