从另一个动态创建的 ComboBox 更新在 Javafx 中动态创建的 ComboBox 的内容

Update the content of a ComboBox dynamically created in Javafx, from another ComboBox dynamically created

GridPane 中,我正在动态创建两个 ComboBox。对于第一个 ComboBox 我在加载场景时对物品进行充电。然后我希望当我在这个 ComboBox 中执行一个动作时,另一个 ComboBox 的项目根据选择的值加载。

ComboBox<String> combobox1 = loadItems();
ComboBox<String> combobox2 = new ComboBox<String>();

gridpane.add(combobox1, 0, 0);
gridpane.add(combobox2, 1, 0);

我试过使用 监听器,但它似乎不起作用:

combobox1.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
    @Override
    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            loadList(combobox2, newValue);
                }
            }); 

private void loadList(ComboBox<String> combobox, String value) {
        combobox = getCorrespondingList(value);
    }

public ComboBox<String> getCorrespondingList(String value) {
        ComboBox<String> combobox = new ComboBox<String>();
        ArrayList<String> list = new ArrayList<String>();
        try {
            String query = "select ... where Item = '" + value 
                    + "' order by c";
            statement = connection.prepareStatement(query);
            result = statement.executeQuery();
            while (result.next()) {
                list.add(result.getString(1));
            }
        }
        catch (SQLException e) {
            e.getMessage();
        }
        ObservableList<String> observableList = FXCollections.observableArrayList(list);
        combobox.setItems(observableList);
        return combobox;
    }

非常感谢任何帮助。

Java 是引用调用。对方法参数的任何赋值只会在方法内部产生影响。此外,据我所知,您确实创建了您想要 修改 ComboBox。而不是创建一个新的 ComboBox,只需填充修改现有的:

private void loadList(ComboBox<String> combobox, String value) {
    combobox.getItems().setAll(getCorrespondingList(value));
}

public List<String> getCorrespondingList(String value) {
    ArrayList<String> list = new ArrayList<String>();
    try {
        // use PreparedStatement's placeholder functionality to avoid
        // issues with quotes inside the string
        String query = "SELECT ... WHERE Item = ? ORDER BY c";
        PreparedStatement ps = connection.prepareStatement(query);
        ps.setString(1, value);

        // no need to keep this after the method exits
        ResultSet rs = ps.executeQuery();

        while (rs.next()) {
            list.add(rs.getString(1));
        }
    } catch (SQLException e) {
        e.printStackTrace(System.err); // should provide more info in case an exception happens
    }
    return list;
}