禁用单个JComboBox项 [英] Disabling individual JComboBox items

查看:67
本文介绍了禁用单个JComboBox项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相当普遍的问题,我使用的解决方案类似于我搜索了什么,后来找到了.一个实现了一个ListCellRenderer和一个JLabel,该JLabel根据当前选定的索引启用或禁用自身:

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

问题在于,即使列表项在外观上显示为已禁用,尽管调用了setFocusable仍然可以将其选中. 我实际上如何禁用它?

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?

推荐答案

您需要某种方法来阻止ComboBox能够设置无法选择的项目.

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

        }

    }

}

现在这是一个快速的技巧来证明这一点.您真正需要的是将某些items标记为不可选择.我想到的最简单的方法是在item中提供一个属性,例如isSelectable.

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.

如果失败,则可以构造一个特殊的ComboBoxModel,该ComboBoxModel维护一个单独的内部模型,该模型包含对所有无法选择的items的引用,因此可以使用快速model.contains(item)来确定该项目是否可以选择或不是.

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.

这篇关于禁用单个JComboBox项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆