【发布时间】:2018-11-07 13:49:46
【问题描述】:
我想在用户选择本科或研究生时过滤学位。我通过互联网搜索,但我无法通过示例代码找到明确的答案。
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);
}
}
});
这是我目前的代码,我该如何解决这个问题?
【问题讨论】:
-
只需在顶部组合框上使用一个侦听器,对第二个框的列表进行排序......请参见此处:stackoverflow.com/questions/58939/… 和此处:stackoverflow.com/questions/17061314/… 提问时您还应该包含一些代码,显示您尝试过的内容(动作侦听器、手动排序、如何创建组合框等)。
-
我可以根据第一个组合选择过滤该列表元素吗?
-
是的,你可以。使用 addActionListener 找出第一个框何时更改,然后从第二个框中删除所有内容并再次将所有元素添加到其中,但顺序正确。请参阅我上面评论中的两个链接。
-
不要使用 ==。请改用 String.equals() 方法,例如:
if(s.equals("Undergraduate Degrees")) {. -
在添加新类别项之前清除 JComboBox:
jComboBox1.removeAllItems();.
标签: java jframe jcombobox netbeans-8 ui-design