Morten Amundsen Morten Amundsen - 2 months ago 46
MySQL Question

How to convert selection in JavaFX ComboBox to String

I have a form which is to be submitted to a mySQL database, where one of the inputs is a ComboBox (JavaFX).

When submitting the input from the ComboBox, the value added to the database is

"ComboBox[id=rolePicker, styleClass=combo-box-base combo-box]"


not a
String
value.

How can I solve this issue, so that the data submitted to the database is a
String
of the value selected?

(Partial) JAVA Controller Code:

public class NewUserController implements Initializable, ControlledScreen {

@FXML
TextField nameField;
@FXML
TextField usernameField;
@FXML
TextField emailField;
@FXML
ComboBox rolePicker;

@FXML
public void submitUser(ActionEvent event) {
String dbUsername = "root";
String dbPassword = "secret";
String dbURL = "jdbc:mysql://localhost:3306/uia";

try {
Connection conn = DriverManager.getConnection(dbURL, dbUsername, dbPassword);
Statement statement = (Statement) conn.createStatement();
statement.execute("INSERT INTO user (name, username, password, email, userrole) VALUES ('" + nameField.getText() + "', '" + usernameField.getText() + "', '" + usernameField.getText() + "', '" + emailField.getText() + "', '" + rolePicker + "');");

} catch (SQLException e) {
System.out.println(e);
}
}


(Partial) FXML Code:

<ComboBox id="rolePicker" fx:id="rolePicker" editable="true" maxHeight="25.0" maxWidth="225.0" minHeight="25.0" minWidth="225.0" prefHeight="25.0" prefWidth="225.0" promptText="Role.." visibleRowCount="4">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="TEACHER" />
<String fx:value="STUDENT" />
</FXCollections>
</items>
</ComboBox>

Answer

On the following line you use rolePicker in a string expression, therefore the compiler will call the toString() method on this object to get the string representation of the object, that causes the mentioned output:

statement.execute("INSERT INTO user (name, username, password, email, userrole) VALUES ('" + 
nameField.getText() + "', '" + usernameField.getText() + "', '" + usernameField.getText() + "', '" + emailField.getText() + 
"', '" + rolePicker + "');");

You should get the selected value of the ComboBox with getValue method:

rolePicker.getValue();

and you can use the returned value in the expression.

Note: getValue will return the type which type the ComboBox has as generic parameter (the type of the items stored in the ComboBox): public final T getValue(). In your current situation you have a ComboBox that stores String values (ComboBox<String>), therefore the returned value can be used directly.