【问题标题】:How to reorganize JCombobox depends on prior choice (Java Swing)如何重组 JCombobox 取决于先前的选择(Java Swing)
【发布时间】:2020-12-13 18:58:12
【问题描述】:

我即将让选择菜单由 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);

【问题讨论】:

  • 如需更好的帮助,请edit 添加minimal reproducible example 或Short, Self Contained, Correct Example。组合框的硬编码数据,首先用 两个 组合框计算出细节。
  • 第一个菜单包含有关“州/省”的信息,下一个菜单打印属于前一个菜单的有关“城市”的列表。
  • Java Swing 以及大多数其他 GUI 库都是在假设您将创建一次 GUI 组件的情况下构建的。创建完所有 GUI 组件后,您可以更新 GUI 组件的内容(文本、图像)。在显示的 GUI 中添加和删除 GUI 组件是一个高级 GUI 主题,必须小心完成。
  • 查看:stackoverflow.com/questions/4982260/binding-comboboxes-in-swing/… 以获得可能的解决方案。

标签: java swing jcombobox


【解决方案1】:

不是每次 ActionListener 激活时都创建一个新的 JComboBox(使用 new JComboBox(...)) 您应该更新现有的 location2/location3-instances。

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

【讨论】:

    猜你喜欢
    • 2021-12-11
    • 2013-09-20
    • 2021-08-12
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    相关资源
    最近更新 更多