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



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;
}

最新更新