Search code examples
javajavafxcomboboxfxml

JavaFX: Populating a ComboBox with data from a MySQL Database, StringConverter breaking the combobox


I have a ComboBox, which I'd like to populate with data from a database. Using the following code, the data that is displayed in the ComboBox is the ID of the value, not the string value.

(Partial) Java Controller Code:

@FXML
    ComboBox studentPicker;
@Override
    public void initialize(URL url, ResourceBundle rb) {
        String dbUsername = "root";
        String dbPassword = "x";
        String dbURL = "jdbc:mysql://localhost:3306/uia";
        try {
            Connection conn = DriverManager.getConnection(dbURL, dbUsername, dbPassword);
            data = FXCollections.observableArrayList();
            // Execute query and store result in a resultset
            ResultSet rs = conn.createStatement().executeQuery("SELECT username FROM user WHERE userrole='STUDENT';");
            while (rs.next()) {
                //get string from db,whichever way 
                data.add(new User(rs.getString("username")));
            }

        } catch (SQLException ex) {
            System.err.println("Error"+ex);
        }

        studentPicker.setItems(null);
        studentPicker.setItems(data);
    }

The StringConverter I tried was picked up from How to import database data into combo box in javafx, but this caused an error with the ComboBox. See image below: Image on the left is how it is supposed to be, right image is how it is when the StringConverter is added to the code.

How it is supposed to be How it is when adding the StringConverter below to the code

studentPicker.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;
        }
    });

What I'd like to display is the usernames collected from the Database, but ID's like "is20x.User@4b6ca8f7" is displayed instead. Any suggestion to how I can solve this problem is greatly appreciated.


Solution

  • Answering from my comment.

    You are adding a new User("username") to your data array which is why you are getting a weird String, its the ID of that particular User.

    Try instead doing data.add(new User(rs.getString("username")).getUserName());, if you User class has a getUserName() method.

    This may break what you are trying to do all around though, as I assume you use data more that just here. It might be best to make another variable and store you comboBox strings in that. So something like

    //Init same place data is
    comboString = FXCollections.observableArrayList(); //Declared somewhere else
    data.add(new User(rs.getString("username")));
    comboString.add(rs.getString("username"));