How do I populate a JavaFX ChoiceBox with data fro

2020-03-24 05:54发布

问题:

private void initialize() {
    loadPersistenceContext();

    List<Events> events = getEventsChoiceBox(getPersistenceContext());
    ObservableList<Event> data = FXCollections.observableList(events);

    cbEvent.setItems(data); // Inserting data into the ChoiceBox
}

This is my main code. Problem is when the form is loaded, I get the Objects inserted in the ChoiceBox and not the properties.

This is the content of my List Events

Object[]
|- String
|- Integer
Object[]
|- String
|- Integer

So I want a ChoiceBox with that String property showing up and the Integer mapped to my controller.

I tried a lot of things but couldn't figure it out.

回答1:

See this example of a JavaFX ChoiceBox control backed by Database IDs.

The example works by defining a Choice class consisting of a database row ID and a string representation of the item to be displayed in the Choice box. The default toString method of Choice is overridden with a custom implementation that returns a string representation of the item to be displayed and not the database ID. When you add the choices to the ChoiceBox, the ChoiceBox will convert each Choice into a string for display. The displayed string value of the Choice is just the choice text rather than also including the database ID or using the default toString of Choice that would just display a meaningless object reference.

Output of choicebox sample app:

Also consider a ComboBox for such an implementation, as it has a mechanisms built into it to abstract the values of nodes from the display of the nodes (via a CellFactory). Use of a ComboBox is however often more complex than a ChoiceBox.



回答2:

Here is another simple implementation from forums.oracle.com

Create a class for key - value

public class KeyValuePair {
   private final String key;
   private final String value;
   public KeyValuePair(String key, String value) {
   this.key = key;
   this.value = value;
   }

  public String getKey()   {    return key;    }

  public String toString() {    return value;  }
}

Then create the ChoiceBox as:

ChoiceBox<KeyValuePair> choiceBox = new ChoiceBox<KeyValuePair>();

Fill the elements as;

choiceBox .getItems().add(new KeyValuePair("1", "Active"));

Hint: Retrive key-value pair from you database into an ArrayList and iterate

To retrieve the value:

choiceBox.getValue().getKey();  // returns the "1"
choiceBox.getValue().toString();  // returns the "Active"


回答3:

Or simply do: myChoiceBox.setConverter(myStringConverter), passing in an instance of your own subclass of javafx.util.StringConverter(JavaDoc).

Overriding the toString (and fromString) gives you full control over how your object is displayed without having to implement a toString in the object itself.



标签: java javafx