Java: Make one item of a jcombobox unselectable(like for a sub-caption) and edit font of that item

只愿长相守 提交于 2019-12-04 10:44:07

Foreword: In the proposed solution I assume that you want to disable items that start with "**". You can change this logic to whatever you want to. In an improved version the MyComboModel class (see below) may even store which items are disabled allowing arbitrary items to be marked disabled.

Solution to your question involves 2 things:

1. Disallow selecting items which you want to be disabled

For this you can use a custom ComboBoxModel, and override its setSelectedItem() method to do nothing if the item to be selected is a disabled one:

class MyComboModel extends DefaultComboBoxModel<String> {
    public MyComboModel() {}
    public MyComboModel(Vector<String> items) {
        super(items);
    }
    @Override
    public void setSelectedItem(Object item) {
        if (item.toString().startsWith("**"))
            return;
        super.setSelectedItem(item);
    };
}

And you can set this new model by passing an instance of it to the JComboBox constructor:

JComboBox<String> cb = new JComboBox<>(new MyComboModel());

2. Display disabled items with different font

For this you have to use a custom ListCellRenderer and in getListCellRendererComponent() method you can configure different visual appearance for disabled and enabled items:

Font f1 = cb.getFont();
Font f2 = new Font("Tahoma", 0, 14);

cb.setRenderer(new DefaultListCellRenderer() {
    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value,
            int index, boolean isSelected, boolean cellHasFocus) {
        if (value instanceof JComponent)
            return (JComponent) value;

        boolean itemEnabled = !value.toString().startsWith("**"); 

        super.getListCellRendererComponent(list, value, index,
                isSelected && itemEnabled, cellHasFocus);

        // Render item as disabled and with different font:
        setEnabled(itemEnabled);
        setFont(itemEnabled ? f1 : f2);

        return this;
    }
});

In order to get what you need, you need to implement ComboBoxEditor.

In this way, you can decide what you want to do in your case, or in any other cases

You could add a custom ItemListener via

addItemListener(ItemListener aListener)

and in that method disable selection or switch selection to item above or so.

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