首页 > 解决方案 > 使用 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

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

初始化组合框

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

标签: javasqlitejavafx

解决方案


您可以获得combo box如下所示的选定值:

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

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

有关更多信息,请参阅组合框


推荐阅读