如何 return 来自 ComboBox 的对象

How to return Object from ComboBox

我在从组合框中检索项目时遇到问题...因此,主要思想是我的对话框 return 是一个 BookDetail 对象,因此我可以将其插入数据库。在这个对话框中,我有我的类别 class 的组合框 - 我希望它 return 到我在 BookDetail 中的构造函数,一个从组合框中选择的项目的类别对象。 我已经在组合框中获得了 category_table 的值,但我无法将选定的类别对象实现到 BookDetail 构造函数中...此块中有很多代码,因此我将仅显示令人沮丧的块。

我想在您现在可以看到的构造函数中 "categoryBox1" 将组合框中选定的类别对象放在那里。有人可以给我建议或示例如何正确地做到这一点吗?我找不到答案...

private void addBook() throws SQLException{
Dialog<BookDetail> dialog = new Dialog<>();

Label categoryLabel1 = new Label("Category: ");


dataCategories = FXCollections.observableArrayList(); // table with categories
ComboBox categoryBox1 = new ComboBox(categoryOptions);
categoryBox1.setMaxHeight(30);

String sql = "select * from tbl_category";
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery(sql);

while(rs.next()){
    dataCategories.add(new Category(rs.getInt(1),rs.getString(2)));
} 

categoryBox1.setItems(dataCategories);

dialog.setResultConverter(new Callback<ButtonType, BookDetail>(){
        @Override
        public BookDetail call(ButtonType b){
            if(b == buttonTypeAdd){

                return new BookDetail(isbnText.getText(),authorText.getText(),categoryBox1,
                        titleText.getText(),publisherText.getText(), dateOfPublicationText.getText(),
                        Integer.parseInt(ratingText.getText()),commentsText.getText());
            }
            return null;
        }
    }); 

}

您可以通过调用 getValue() 获取 ComboBox 的选定(或用户编辑)值。

因此,在您的 BookDetail 构造函数中,不是通过 categoryBox1 引用传入 ComboBox 本身,而是只传入组合框中的选定值:

categoryBox1.getValue()