繁体   English   中英

如何从侦听器禁用Jcombobox项?

[英]How to disable a Jcombobox item from a listener?

我的项目有问题,因为我的目标是让用户用数组中的项目手动填充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); 将使JComboBox具有list项目。 因为在内部类ActionListener内调用了c1,所以使用了final事件,该类用于单击事件。 index=c1.getSelectedIndex(); 将获得c1所选项目的index location c2.removeItemAt(index); 将删除位于c2 index位置的项目。 由于c1c2都包含相似的项目,因此项目的index位置相同。 如果要在某点上重新插入c2中的项目,则使用来保存要删除的项目的索引位置和要删除的项目的名称。

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

然后使用

c2.insertItemAt(item,index);

注意 -如果要在indexitem之外ActionListener则应在ActionListener之外声明。

尝试启用ComboItem。 函数setEnabled用于对象,具体情况为cb2。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM