使用JavaFX中的自定义属性填充ChoiceBox

时间:2016-11-17 02:43:45

标签: javafx javafx-8

如何填写ChoiceBox例如来自我的自定义类的StringProperty

我只使用ChoiceBox在SceneBuilder中进行设计,并且我的数据有Person类。

public class Person{
    private final StringProperty firstName;

    public Person(){
        this(null);
    }

    public Person(String fname){
        this.firstName = new SimpleStringProperty(fname);
    }

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

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

    public StringProperty firstNameProperty(){
        return this.firstName;
    }
}

在大班我有:

private ObservableList<Person> personList = FXCollections.observableArrayList();
this.personList.add(new Person("Human1"));

RootController controller = loader.getController();
        controller.setChoiceBox(this);

public ObservableList<Person> getPersonList(){
    return this.personList;
}

在我的控制器中:

public class RootController {
    @FXML
    private ChoiceBox personBox;

    public RootController(){

    }

    @FXML 
    private void initialize(){

    }

    public void setChoiceBox(App app){

        personBox.setItems(app.getPersonList());
    }


}

但是这个代码用函数名(??)或类似的东西填充我的ChoiceBox。 如何用firstName属性填充它?

2 个答案:

答案 0 :(得分:1)

请注意,通过在此处使firstName属性可变,您已经创建了一个大问题。

AFAIK不可能让ChoiceBox听取对该属性的修改(至少在没有替换skin的情况下,这将非常复杂)。

这可以通过ComboBox来完成。

您只需使用自定义cellFactory

private ListCell<Person> createCell(ListView<Person> listView) {
    return new ListCell<Person>() {

        @Override
        protected void updateItem(Person item, boolean empty) {
            super.updateItem(item, empty);

            if (empty || item == null) {
                textProperty().unbind();
                setText("");
            } else {
                textProperty().bind(item.firstNameProperty());
            }
        }

    };
}
ComboBox<Person> cb = new ComboBox<>(personList);
cb.setCellFactory(this::createCell);
cb.setButtonCell(createCell(null));
...

答案 1 :(得分:0)

对于你的问题,我建议使用'最简单的方法'。 ChoiceBox 使用 Person 类的toString()方法,产生类似{ {1}}。

通过覆盖choiceBox.Person@18f8865方法,您可以定义ChoiceBox将显示的内容。在您的情况下,返回toString()属性的值:

firstName