panekola12
panekola12

Reputation: 31

Filling ChoiceBox with custom property in JavaFX

How can I fill ChoiceBox with e.g. a StringProperty from my custom class?

I have simply design in SceneBuilder with a ChoiceBox and I have a Person class with my data.

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

In main class I have:

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

And in my controller:

public class RootController {
    @FXML
    private ChoiceBox personBox;

    public RootController(){

    }

    @FXML 
    private void initialize(){

    }

    public void setChoiceBox(App app){

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


}

But this code fill my ChoiceBox by function name(??) or something like that. How can I fill it with the firstName property?

Upvotes: 0

Views: 614

Answers (2)

fabian
fabian

Reputation: 82531

Note that you've created yourself a big problem by making the firstName property mutable here.

AFAIK it's not possible to make ChoiceBox listen to modifications of that property (at least not without replacing the skin, which would be awfully complicated).

This could be done with a ComboBox however.

You just need to use a custom 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));
...

Upvotes: 1

SSchuette
SSchuette

Reputation: 619

For your problem I would suggest to use the 'easiest way'.The ChoiceBox uses the toString() method of the Person class resulting in something like choiceBox.Person@18f8865.

By overriding the toString() method you can define what the ChoiceBox will display. In your case return the value of the firstName property:

@Override
public String toString() {
    return firstName.get();
}

Upvotes: 0

Related Questions