如何禁用JComboBox中的某些项目 [英] How to disable certain items in a JComboBox

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

问题描述

我有一个ComboBox,其中有8个项目,除了某些条件外,我想显示所有项目,用户只能选择其中的前两个项目,因此,我将其编程为如果条件为true,则用户选择任何其他选项,然后会显示一个消息框,显示"You cannot choose this",然后自动选择默认值.到目前为止一切顺利.

I have a ComboBox in which I have 8 Items out of which I want to display all but on a certain condition, the user should only be able to select the first two of them, so I have programmed that if the condition is true and the user chooses any other option then it shows up a Message Box showing "You cannot choose this" and then selecting the default automatically. So far so good.

但是现在的问题是,用户无法通过查看JComboBox的选项来辨别出自己可以选择的选项,所以我想做的是,如果条件为true,则除第一个选项外的所有选项应该禁用两个(或变灰或其他),以便用户可以识别出您无法选择它,如果他们仍然选择了,则应该出现我的消息框.

But now the thing is that the user cannot make out by seeing the options of JComboBox that which ones can he select, So what I want to do is that if the condition is true then all the options other than the first two should be disabled(or grey out or something) so that users can make out that you cannot select it, and if they still do then my Message Box should come up.

我尝试过的事情:我尝试查找,但是我无法弄清楚问题中做了什么(答案对我没有用),我也尝试了其他选择,但未成功.

What I tried: I tried looking up this but I couldn't make out what was done in the question (it's answer is for no use for me) and I also tried other options but was unsuccessful.

注意:我正在使用Netbeans GUI创建所有内容,并且正在编写的代码在JComboBoxActionPerformed上,并且我是新手,所以我不知道自己对此表示歉意

Note: I am using Netbeans GUI to create everything, and the code I am writing is on JComboBoxActionPerformed and I am a newbie so I couldn't figure out myself, apologies for that

推荐答案

首先...

这将需要一些手工编码. GUI Builder不会在这里为您提供帮助.

First of all...

This is going to require some hand coding. The GUI Builder is not going to help you out here.

您可以实现自己的BasicComboBoxRenderer,并在其中传递ListSelectionModel.根据传递给它的模型,只有选定的时间间隔将使用标准渲染器进行渲染.其余索引将通过更改前景色及其选择背景以 disable 的方式呈现.

You can implement your own BasicComboBoxRenderer, where you pass to it a ListSelectionModel. Based on the model you pass to it, only the selected interval will get rendered with the standard renderer. The remaining indices will get rendered in a disable fashion, by change the foreground color and it's selection background.

注意:这只会影响项目的呈现,而不会影响实际的选择事件

Note: this is only going to affect the rendering of the items, not the actual selection events

import java.awt.Color;
import java.awt.Component;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicComboBoxRenderer;

public class EnabledComboBoxRenderer extends BasicComboBoxRenderer {

    private ListSelectionModel enabledItems;

    private Color disabledColor = Color.lightGray;

    public EnabledComboBoxRenderer() {}

    public EnabledComboBoxRenderer(ListSelectionModel enabled) {
        super();
        this.enabledItems = enabled;
    }

    public void setEnabledItems(ListSelectionModel enabled) {
        this.enabledItems = enabled;
    }

    public void setDisabledColor(Color disabledColor) {
        this.disabledColor = disabledColor;
    }

    @Override
    public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus) {

        Component c = super.getListCellRendererComponent(list, value, index,
                isSelected, cellHasFocus);

        if (!enabledItems.isSelectedIndex(index)) {// not enabled
            if (isSelected) {
                c.setBackground(UIManager.getColor("ComboBox.background"));
            } else {
                c.setBackground(super.getBackground());
            }

            c.setForeground(disabledColor);

        } else {
            c.setBackground(super.getBackground());
            c.setForeground(super.getForeground());
        }
        return c;
    }
}

您可以使用两个单独的侦听器.一种用于启用项目时,另一种用于禁用项目时.启用项目后,您可以 1..更改选择模型 2.添加已启用的侦听器 3.删除已禁用的侦听器

You can use two separate listeners. One for when the items are enabled and one for when the items are disabled. When the items are enabled, you can 1. Change the selection model 2. Add the enabled listener 3. Remove the disabled listener

private class EnabledListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(((JComboBox) e.getSource()).getSelectedItem());
    }
}

private class DisabledListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (((JComboBox) e.getSource()).getSelectedIndex() != SELECTION_INTERVAL[0]
                && ((JComboBox) e.getSource()).getSelectedIndex() != SELECTION_INTERVAL[1]) {
            JOptionPane.showMessageDialog(null,
                    "You can't Select that Item", "ERROR",
                    JOptionPane.ERROR_MESSAGE);
        } else {
            System.out.println(((JComboBox) e.getSource())
                    .getSelectedItem());
        }
    }
}

protected void enableItemsInComboBox() {
    comboBox.removeActionListener(disabledListener);
    comboBox.addActionListener(enabledListener);
    model.setSelectionInterval(SELECTION_INTERVAL[0], comboBox.getModel()
        .getSize() - 1);
}

反之亦然

protected void disableItemsInComboBox() {
    comboBox.removeActionListener(enabledListener);
    comboBox.addActionListener(disabledListener);
    model.setSelectionInterval(SELECTION_INTERVAL[0], SELECTION_INTERVAL[1]);
}

这是一个完整的运行示例,使用上方的EnabledComboBoxRenderer

Here's a complete running example, using EnabledComboBoxRenderer from above

import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.DefaultListSelectionModel;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class ComboBoxDisabledItemsDemo {
    private static final int[] SELECTION_INTERVAL = { 0, 1 };

    private JComboBox comboBox;
    private JCheckBox disableCheckBox;
    private DefaultListSelectionModel model = new DefaultListSelectionModel();
    private EnabledComboBoxRenderer enableRenderer = new EnabledComboBoxRenderer();

    private EnabledListener enabledListener = new EnabledListener();
    private DisabledListener disabledListener = new DisabledListener();

    public ComboBoxDisabledItemsDemo() {
        comboBox = createComboBox();

        disableCheckBox = createCheckBox();
        disableCheckBox.setSelected(true); // this adds the action listener to
                                            // the
                                            // to the combo box

        JFrame frame = new JFrame("Disabled Combo Box Items");
        frame.setLayout(new GridBagLayout());
        frame.add(comboBox);
        frame.add(disableCheckBox);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private JComboBox createComboBox() {
        String[] list = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5",
                "Item 6", "Item 7" };
        JComboBox cbox = new JComboBox(list);
        model.addSelectionInterval(SELECTION_INTERVAL[0], SELECTION_INTERVAL[1]);
        enableRenderer.setEnabledItems(model);
        cbox.setRenderer(enableRenderer);
        return cbox;
    }

    private class EnabledListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println(((JComboBox) e.getSource()).getSelectedItem());
        }
    }

    private class DisabledListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (((JComboBox) e.getSource()).getSelectedIndex() != SELECTION_INTERVAL[0]
                    && ((JComboBox) e.getSource()).getSelectedIndex() != SELECTION_INTERVAL[1]) {
                JOptionPane.showMessageDialog(null,
                        "You can't Select that Item", "ERROR",
                        JOptionPane.ERROR_MESSAGE);
            } else {
                System.out.println(((JComboBox) e.getSource())
                        .getSelectedItem());
            }
        }
    }

    protected void disableItemsInComboBox() {
        comboBox.removeActionListener(enabledListener);
        comboBox.addActionListener(disabledListener);
        model.setSelectionInterval(SELECTION_INTERVAL[0], SELECTION_INTERVAL[1]);
    }

    protected void enableItemsInComboBox() {
        comboBox.removeActionListener(disabledListener);
        comboBox.addActionListener(enabledListener);
        model.setSelectionInterval(SELECTION_INTERVAL[0], comboBox.getModel()
                .getSize() - 1);
    }

    private JCheckBox createCheckBox() {
        JCheckBox checkBox = new JCheckBox("diabled");
        checkBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    disableItemsInComboBox();
                } else if (e.getStateChange() == ItemEvent.DESELECTED) {
                    enableItemsInComboBox();
                }
            }
        });
        return checkBox;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ComboBoxDisabledItemsDemo();
            }
        });
    }
}

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

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