Disabling individual JComboBox items

做~自己de王妃 提交于 2019-12-01 06:49:12

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.

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