如何将 JavaFX ComboBox 中的选择转换为字符串

How to convert selection in JavaFX ComboBox to String

我有一个要提交给 mySQL 数据库的表单,其中一个输入是 ComboBox (JavaFX)。

从ComboBox提交输入时,添加到数据库的值为

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

不是 String 值。

如何解决这个问题,使提交到数据库的数据是所选值的String

(部分)JAVA 控制器代码:

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

(部分)FXML 代码:

<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>

在下一行中,您在字符串表达式中使用了 rolePicker,因此编译器将调用此对象的 toString() 方法来获取对象的字符串表示形式,这会导致上述输出:

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

您应该使用 getValue 方法获取 ComboBox 的选定值:

rolePicker.getValue();

您可以在表达式中使用 returned 值。

注意: getValue 将 return ComboBox 的类型作为泛型参数(存储在ComboBox): public final T getValue()。在您当前的情况下,您有一个存储 String 值 (ComboBox<String>) 的 ComboBox,因此可以直接使用 returned 值。