问题描述
我要使选择菜单包含3个JComboBox,它们与先前的选择有关。
选择第一个菜单时,我需要通过请求JSON更新下一个JComboBox,以此类推,以获取最后一个菜单。
我试过的方法:放置addActionListener来更新下一个JComboBox,但似乎不起作用。
很难找到问题,因为我无法通过调试器捕获它。
方法“ getParsedData”返回JSONArray来自JSON文件。
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);
解决方法
与其在每次ActionListener处于活动状态时都创建一个新的JComboBox(使用new JComboBox(...))
,您应该更新现有的location2 / location3-instances。
对于location2,您可以先致电
location2.removeAllItems()
。之后,您应该遍历mdList并为每个mdList项调用location2.addItem()
。