如何重组 JCombobox 取决于事先选择 (Java Swing)

How to reorganize JCombobox depends on prior choice (Java Swing)

我要让选择菜单由3个JCombobox组成,它们与优先选择有关。
当我选择第一个菜单时,我需要通过请求 JSON 更新下一个 JCombobox,最后一个菜单依此类推。
我尝试了什么:将 addActionListener 用于更新下一个 JCombobox,但它似乎不起作用。
很难找到问题,因为我无法通过调试器捕获它。
方法 'getParsedData' returns JSON 数组来自 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.

对于位置 2,您可以先调用 location2.removeAllItems()。之后你应该遍历你的 mdList 并为每个 mdList-item.

调用 location2.addItem()