How to import database data into combo box in java

2019-08-09 06:25发布

问题:

Using this code I Initialized Combo box

@FXML
private ComboBox category;

And get value using:

String Category = category.getValue().toString();

And inserted value to mysql database. Now before inserting next value in category Combo box I need to import the values in the database to the drop down in Combo Box and value should be displayed in the combo box.

回答1:

I recommend to read the values from the database and save it into a ObservableList, once you get all the values you can fill the combobox with:

 combobox.setItems(myObservableList);

if your type of combobox is not "String" you should use a String converter, for example, if you wanna fill the combobox with the name of users, being "user" a class and name an attribute, you just have to:

myCombo.setConverter(new StringConverter<user>() {

            @Override
            public String toString(user object) {
                return object.getName();
            }

            @Override
            public user fromString(String string) {
                // TODO Auto-generated method stub
                return null;
            }
        });