如何重新组织JCombobox取决于先前的选择(Java Swing)
我将使选择菜单由3个JComboBox组成,它们与先前的选择相关。如何重新组织JCombobox取决于先前的选择(Java Swing),java,swing,jcombobox,Java,Swing,Jcombobox,我将使选择菜单由3个JComboBox组成,它们与先前的选择相关。 当我选择第一个菜单时,我需要通过请求JSON更新下一个JCombobox,依此类推最后一个菜单。 我尝试的是:将addActionListener放在下一个JCombobox更新中,但它似乎不起作用。 很难找到问题,因为我无法通过调试器捕获它。 方法“getParsedData”返回来自JSON文件的JSONArray JPanel test = new JPanel(); test.setLay
当我选择第一个菜单时,我需要通过请求JSON更新下一个JCombobox,依此类推最后一个菜单。
我尝试的是:将addActionListener放在下一个JCombobox更新中,但它似乎不起作用。
很难找到问题,因为我无法通过调试器捕获它。
方法“getParsedData”返回来自JSON文件的JSONArray
JPanel test = new JPanel();
test.setLayout(new FlowLayout());
add(test);
top = rc.getParsedData("top");
ArrayList<String> topList = rc.getLocationList(top);
location1 = new JComboBox(topList.toArray(new String[topList.size()]));
location1.addActionListener(e -> {
try {
rc.setCode(top, location1.getSelectedItem().toString());
mdl = rc.getParsedData("mdl");
ArrayList<String> mdlList = rc.getLocationList(mdl);
location2 = new JComboBox(mdlList.toArray(new String[mdlList.size()]));
} catch (IOException | ParseException ioException) {
ioException.printStackTrace();
}
});
test.add(location1);
location2.addActionListener(e -> {
try {
leaf = rc.getParsedData("leaf");
rc.setCode(mdl, location2.getSelectedItem().toString());
ArrayList<String> leafList = rc.getLocationList(leaf);
location3 = new JComboBox(leafList.toArray(new String[leafList.size()]));
rc.setXY(leaf, location3.getSelectedItem().toString());
} catch (IOException | ParseException ioException) {
ioException.printStackTrace();
}
});
test.add(location2);
test.add(location3);
JPanel测试=新的JPanel();
test.setLayout(新的FlowLayout());
添加(测试);
top=rc.getParsedData(“top”);
ArrayList topList=rc.getLocationList(顶部);
location1=newjcombobox(topList.toArray(新字符串[topList.size()]);
位置1.addActionListener(e->{
试一试{
rc.setCode(顶部,位置1.getSelectedItem().toString());
mdl=rc.getParsedData(“mdl”);
ArrayList mdlList=rc.getLocationList(mdl);
location2=newjcombobox(mdlList.toArray(新字符串[mdlList.size()]);
}catch(IOException | ParseException IOException){
ioException.printStackTrace();
}
});
测试。添加(位置1);
位置2.addActionListener(e->{
试一试{
leaf=rc.getParsedData(“leaf”);
rc.setCode(mdl,location2.getSelectedItem().toString());
ArrayList leafList=rc.getLocationList(leaf);
location3=newjcombobox(leafList.toArray(新字符串[leafList.size()]);
rc.setXY(叶,位置3.getSelectedItem().toString());
}catch(IOException | ParseException IOException){
ioException.printStackTrace();
}
});
测试。添加(位置2);
测试。添加(位置3);
您应该更新现有的location2/location3实例,而不是每次ActionListener激活时都创建一个新的JComboBox(使用新的JComboBox(…)
)
对于位置2,您可以先致电
location2.removeAllItems()
。之后,您应该遍历mdList,并为每个mdList项调用location2.addItem()
。要更快获得更好的帮助,请添加或。组合框的硬代码数据&首先用两个组合框计算出详细信息。第一个菜单包含关于“州/省”的信息,下一个菜单打印属于前一个菜单的关于“市”的列表。Java Swing以及大多数其他GUI库都是在假设您将一次性创建GUI组件的情况下构建的。创建所有GUI组件后,可以更新GUI组件的内容(文本、图像)。从显示的GUI中添加和删除GUI组件是一个必须小心完成的高级GUI主题。请查看:以获取可能的解决方案。