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.

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.

1

2 Answers

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"));
1

I want to share what I did to automatically set the data from MySQL database. (that is very simple)

        // first I execute the query that select name of department one by one
        resultSet = statement.executeQuery("Select name from department");

        while (resultSet.next()) {  // loop

           // Now add the comboBox addAll statement 
            comboBox.getItems().addAll(resultSet.getString("name")); 
       }

note here the "name" field in last line, is exactly spelled same as the name of the column in MySQL table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest