简体   繁体   English

Java从UserList和setItems ComboBox获取用户名

[英]Java get UserName from UserList and setItems ComboBox

I have this: 我有这个:

@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);

I do not like the two list and the loop. 我不喜欢这两个列表和循环。 I wonder if you can only download users' logins directly from the userList list and place them ChoiseBox 我想知道您是否只能直接从userList列表中下载用户的登录名并将其放置在ChoiseBox中

Class User: 班级用户:

private IntegerProperty userLp;
private StringProperty userLogin;
private StringProperty userRule;

Most probably, you don't want to have the ChoiceBox items as a list that's mapped once (somehow) from the real items because doing so comes with a handful of disadvantages: 最有可能的是,您不想将ChoiceBox项作为从真实项一次映射(以某种方式)的列表,因为这样做有一些缺点:

  • the two lists can get easily out off sync: when the users change or any its properties, the ChoiceBox is not updated 这两个列表很容易脱离同步:当用户更改或其任何属性时,ChoiceBox不会更新
  • when listening to fi selection changes in the ChoiceBox, the listener doesn't have the complete information about the user (from the selectedItem) but just one of its property values - if it wants to act on the user, it would have to look it up the info somewhere else, thus introducing (unwanted) coupling 当侦听ChoiceBox中的fi选择更改时,侦听器不具有有关用户的完整信息(来自selectedItem),而只有其属性值之一-如果要对用户执行操作,则必须查找它在其他地方获取信息,从而引入(不需要的)耦合
  • you are fighting the winds of fx, which has dedicated support to configure visual representations of any data object - in the case of a ChoiceBox you'd need a StringConverter 您正在抵御fx的风,fx具有专用支持来配置任何数据对象的可视表示形式-如果使用ChoiceBox,则需要一个StringConverter

Example code snippet: 示例代码段:

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

使用Java 8流

choiseData.getItems().addAll(userList.stream().map(User::getUserLogin()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM