java - 如何根据第一个组合框选择过滤第二个组合框中的内容

标签 java jframe jcombobox netbeans-8 ui-design

我想在用户选择本科或研究生时过滤学位。我通过互联网搜索,但找不到带有示例代码的明确答案。

      private String[] itemsUndergraduate = new String[]{"Computer Science", "Software Engineering"};
    private String[] itemsPostgraduate = new String[]{"BA", "Msc"};
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
   UPselect.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
    String[] itemsUndergraduate = new String[]{"Computer Science", "Software Engineering"};
    String[] itemsPostgraduate = new String[]{"BA", "Msc"};
    String s = (String) UPselect.getSelectedItem();
    if (s.equals("Undergraduate Degrees")){
        //Assign the first list to the combobox
        jComboBox1 = new JComboBox(itemsUndergraduate);
    }
    else{
        //Assign the second list to the combobox
        jComboBox1 = new JComboBox(itemsPostgraduate);
    }
}

});

这是我到目前为止的代码,我该如何解决这个问题?

最佳答案

根据您的评论和更新的代码,是的,您走在正确的道路上。

这是一个例子。首先,我们需要两个列表供以后使用。

String[] itemsUndergraduate = new String[]{"Computer Science", "Software Engineering"};
String[] itemsPostgraduate = new String[]{"BA", "Msc"};

现在,当选择第一个组合框时,我们可以更改第二个组合框的内容以匹配其中一个列表:

UPselect.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e){
        String s = (String) UPselect.getSelectedItem();

        //Added this line to help you debug the code
        System.out.print("Does this bit of code ever happen??");
        System.out.print("Value of selected item is: "+s);

        if (s.equals("Undergraduate Degrees")){
            //Assign the first list to the combobox
            jComboBox1 = new JComboBox(itemsUndergraduate);
        }
        else{
            //Assign the second list to the combobox
            jComboBox1 = new JComboBox(itemsPostgraduate);
        }
    }
}

关于java - 如何根据第一个组合框选择过滤第二个组合框中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50575329/

相关文章:

java - 使用 J2s [Auto complete ComboBox] 的 JTable 自动完成不工作

java - 设置 JTable、Java 的条件

java - 寻找语法宽松的 JSON 库

java - 同步方法递归调用自身。这是坏了吗?

java - Google Protocol 重复值的结构是怎样的?它们的局限性和优势是什么?

java - 在 JPanel 中在图像上绘制形状

java - JTable、JComboBox 动态值

java - 使用 UISpec4J 或 FEST 的优缺点

java - JFrame关闭后如何执行操作?

JAVA - 从 Action 监听器调用时 JFrame 看起来不正确