使用javafx将选择的值上传到数据库时,如何在组合框中仅显示选择的值

时间:2019-04-23 12:16:55

标签: java sqlite javafx

所以我现在遇到的问题是我可以用新用户更新数据库,但是它不能显示角色列的正确数据,因为它是从组合框中选择的,它显示了整个组合框选择,而不只是选定的选择。问题如下链接所示。 https://imgur.com/a/XeDinn9

AddUsers方法

public static void addUsers(String username, String password, String role, String staff_id) {

try {
            Connection conn = DBConnection.getConnection();

            String sql = "INSERT into Login(username, password, role, staff_id) VALUES(?,?,?,?)";

            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            ps.setString(3, role);
            ps.setString(4, staff_id);

            ps.executeUpdate();
            conn.close();

        } catch (SQLException ex)
        {

        }

    }

userRoleBox的可观察列表

ObservableList<String> userRoleList = FXCollections.observableArrayList("Admin", "Technician", "Finance", "Management", "Customer Services");

初始化comboBox

@FXML
    private void initialize()
    {
     userRoleBox.setValue("Technician");
     userRoleBox.setItems(userRoleList);
    }

单击确认按钮将用户添加到数据库中时初始化的方法

    @FXML
    public void ConfirmUsers(ActionEvent event) throws SQLException, ClassNotFoundException
    {
        if(usernametxtfld.getText().isEmpty() || passwordtxtfld.getText().isEmpty() || userRoleBox.getItems().isEmpty() || staffIDtxtfld.getText().isEmpty())
        {
            Alert errorAlert = new Alert(Alert.AlertType.ERROR);
            errorAlert.setHeaderText("Please fill in all of the fields");
            errorAlert.setContentText("Click OK and ensure you have entered information in all of the boxes.");
            errorAlert.showAndWait();

        }
        else{

            CreateUsersDAO.addUsers(usernametxtfld.getText(),passwordtxtfld.getText(),userRoleBox.getItems().toString(),staffIDtxtfld.getText());
            clearFields();
            Alert confirmation = new Alert(Alert.AlertType.INFORMATION);
            confirmation.setHeaderText("New user has been added.");
            confirmation.showAndWait();
       }
    }

1 个答案:

答案 0 :(得分:1)

您可以像下面这样选择combo box值:

userRoleBox.getSelectionModel().getSelectedItem();//will give you single item selected

将功能userRoleBox.getItems().toString()中的参数更改为userRoleBox.getSelectionModel().getSelectedItem();

有关更多信息,请参见 ComboBox