2016-11-12 78 views
1

我有一个从组合框中取回项目的问题...所以,主要想法是我的对话框返回一个BookDetail对象,以便将其插入到数据库中。在这个对话框中,我有我的Category类的组合框 - 我期望它返回到我的构造函数BookDetail一个类别对象,它是从组合框中选择的项目。 我已经从我的category_table组合框的值,但我不能实现选定的类别对象到BookDetail的构造函数...有很多代码在这个块,所以我只会显示挫败块。如何从组合框返回对象

我想在该构造函数中,您现在可以看到“categoryBox1”从combobox中放入所选的Category对象。有人可以给我建议或例子如何正确地做到这一点?

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

}

回答

1

你可以得到的选择(或用户编辑)组合框的值通过调用getValue()我无法找到答案......。

因此,在你BookDetail构造函数,而不是通过categoryBox1参考在ComboBox本身传球,而不是只在选定的值传递从下拉列表框:

categoryBox1.getValue() 
+0

没错,就是它! :) –