我有这个:
@FXML
private ChoiceBox<String> choiseData;
ObservableList<String> choiseUserList = FXCollections.observableArrayList();
ObservableList<User> userList = FXCollections.observableArrayList();
AdminSQL sql = new AdminSQL();
userList = sql.getAllUser();
for (User u : userList)
choiseUserList.add(u.getUserLogin());
choiseData.setItems(choiseUserList);
我不喜欢这两个列表和循环。我想知道你是否只能直接从userList列表下载用户登录并将它们放在ChoiseBox
班级用户:
private IntegerProperty userLp;
private StringProperty userLogin;
private StringProperty userRule;
答案 0 :(得分:1)
最有可能的是,你不希望将ChoiceBox项目作为从真实项目中映射一次(不知何故)的列表,因为这样做会带来一些缺点:
示例代码段:
ChoiceBox<User> choiceBox = new ChoiceBox<>(getUsers());
// from your snippet, AdminSQL already returns the list as
// an ObservableList, so you can set it directly as provided
// new ChoiceBox<>(sql.getAllUsers());
StringConverter<User> converter = new StringConverter<>() {
@Override
public String toString(User user) {
return user != null ? user.getUserLogin() : "";
}
@Override
public User fromString(String userLogin) {
// should never happen, choicebox is not editable
throw new UnsupportedOperationException("back conversion not supported from " + userLogin);
}
};
choiceBox.setConverter(converter);
答案 1 :(得分:0)
使用Java 8 Streams
choiseData.getItems().addAll(userList.stream().map(User::getUserLogin()));