如何将ComboBox的项绑定到另一个列表项的属性?

时间:2018-02-24 02:43:51

标签: java javafx data-binding

我有一个简单的User类,它包含两个属性:

public class User {
    private final StringProperty lastName;
    private final StringProperty firstName;

    public User() {
        lastName = new SimpleStringProperty("");
        firstName = new SimpleStringProperty("");
    }

    public User(
            String lastName,
            String firstName
    ) {
        this.lastName = new SimpleStringProperty(lastName);
        this.firstName = new SimpleStringProperty(firstName);
    }

    public String getFirstName() { return firstName.get(); }

    public String getLastName() { return lastName.get(); }

    public void setFirstName(String firstName) { this.firstName.set(firstName); }

    public void setLastName(String lastName) { this.lastName.set(lastName); }
}

我创建了一个包含ComboBoxUser的窗口:

public class WindowController {
    @FXML
    private ComboBox<User> usersComboBox;

    public void setUserList(ObservableList<User> userList) { }
}

我希望setUserListuserList绑定到usersComboBox,以便每个ComboBox的{​​{1}}个项为u.firstName.get() + " " + u.lastName.get() u。每次userList中添加,删除或修改ComboBox时,User都必须刷新其项目。

我已经阅读过关于JavaFX中的绑定,但我找不到如何做到这一点。推荐的方式是什么?

1 个答案:

答案 0 :(得分:0)

我希望我能正确理解你。

如果是这样,我确实有一些示例代码:

import java.util.ArrayList;
import java.util.List;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class MainApp extends Application
{
    private BorderPane root = new BorderPane();
    private Scene szene = new Scene(root);

    @Override
    public void start(Stage primaryStage) throws Exception
    {
        ComboBox<String> comboBox = new ComboBox<String>();

        List<User> list = new ArrayList<User>();
        ObservableList<User> userList = FXCollections.observableList(list);
        userList.addListener(new ListChangeListener<Object>() {

            @Override
            public void onChanged(Change<?> change)
            {
                comboBox.getItems().clear();
                for(User u : userList)
                {
                    comboBox.getItems().add(u.getName());
                }
            }
        });

        userList.add(new User("Max", "Mustermann"));
        userList.add(new User("Adam", "Sandler"));
        userList.add(new User("Jan", "Boehmermann"));

        root.setCenter(comboBox);

        primaryStage.setScene(szene);
        primaryStage.show();
    }

    public static void main(String[] args)
    {
        launch(args);
    }
}

您可以简单地实例化一个List并将其交给FXCollections.observableList()。然后将一个ListChangeListener添加到ObservableList,它会在更改时更新ComboBox(显然)。

请记住,在添加每个元素之前必须清除ObservableList以防止加倍。不要向ArrayList添加元素,或者记住对ArrayList的更改不会触发ObservableList的ListChangeListener!