如何从侦听器禁用 Jcombobox 项



我的项目有问题,因为我的目标是让用户用数组中的项目手动填充 6 个字段;我想到了 6 个具有相同项目的JComboBox es,当您在一个框中选择一个项目时,它在其余项目中被禁用。我正在开始,尽管我已经搜索过,但我只在其构造函数中找到了执行此操作的方法。

cb1.addActionListener(new ActionListener(){ 
@Override
public void actionPerformed(ActionEvent e) {
     if(cb1.getSelectedIndex()==1) {
         // this is as far as I go, but disables the entire jcombobox
         cb2.setEnabled(false);
         // this is more like I want, but it doesn't work.
         cb2.setSelectedIndex(1).setEnabled(false);                            
 }}});

如果有人知道一种更有效的方法,使用户能够手动将数组项目分配给许多字段,我将表示欢迎。

您无法禁用JComboBox项。您可以将其从此处的位置删除,方法是:-

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class Combobox extends JFrame{
Combobox(){
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    String[] list={"car","bus","bike"};
    final JComboBox c1=new JComboBox(list);
    final JComboBox c2=new JComboBox(list);
    Container c=this.getContentPane();
    c.setLayout(new FlowLayout());
    c.add(c1);
    c.add(c2);
    c1.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            int index=c1.getSelectedIndex();
            c2.removeItemAt(index);
            }
    });
    this.pack();
}
    public static void main(String[] args) {
        new Combobox();
    }
}

final JComboBox c1=new JComboBox(list);会让一个JComboBoxlist物品。 使用 final 是因为 C1 在内部类 ActionListener 中调用,用于单击事件。 index=c1.getSelectedIndex();将在c1中获取所选项目的index locationc2.removeItemAt(index);将删除位于 C2 位置index的项目。由于c1c2都包含相似的项目index因此项目的位置是相同的。如果您想在某个时候在 c2 中重新插入该项目,那么保存要删除的项目的索引位置和要删除的项目的名称,使用

index=c1.getSelectedIndex();
item=c2.getItemAtIndex(index);
c2.removeItemAt(index);

然后使用

c2.insertItemAt(item,index);

注意 - 如果要在外部使用indexitem,则应在ActionListener外部声明。

尝试启用 ComboItem。函数 setEnabled 用于对象,在您的案例中 cb2。

最新更新