简体   繁体   English

从ComboBox获取对象

[英]get object from ComboBox

Here is my problem. 这是我的问题。 I have a generic class called FilteredComboBox that extends ComboBox. 我有一个名为FilteredComboBox的通用类,该类扩展了ComboBox。 It is basically an editable combobox that filteres choices according to user input. 它基本上是一个可编辑的组合框,可以根据用户输入过滤选择。 This FilteredCombobox is feed by ObservableList of type Book, which is just a simple class with 2 fields, name and id (obviously it has getters, setters and toString). 这个FilteredCombobox由Book类型的ObservableList提供,这是一个简单的类,具有2个字段,名称和ID(显然,它具有getters,setters和toString)。

After user makes his choice and clicks on book that he wants from the dropdown, I would like to get this book id by the method in book class called getBookId. 用户做出选择并从下拉列表中单击所需的书后,我想通过名为getBookId的书类中的方法获取该书ID。 Unfortunately when I say bookComboBox.getValue.getBookId I get cast exception, because getValue automatically calls toString method. 不幸的是,当我说bookComboBox.getValue.getBookId时,我得到了强制转换异常,因为getValue自动调用toString方法。 Is there a way around it? 有办法解决吗? I would like to make getValue() method to return an object of type book and just a\\call my getBookId() from there. 我想使getValue()方法返回book类型的对象,然后从那里调用我的getBookId()。

Any ideas? 有任何想法吗?

For combo like 对于像

ComboBox<Book> combobox = new ComboBox<>(your_book_list);

get the selected book item on event (on button action event for instance) 获取事件中的所选书籍项目(例如,按钮操作事件)

Book selectedBook = combobox.getSelectionModel().getSelectedItem();
Integer id = selectedBook.getBookId();

Yes it does extend ComboBox I solved my problem by doing his: 是的,它的确扩展了ComboBox的功能。

public T getChosenValue() {
int index = getSelectionModel().getSelectedIndex();
if(filter.size() != 0)
{
       System.out.println("filter size is not 0");
       return filter.get(index);
}
else
{
System.out.println("filter size is 0");
return items.get(index);
}
} 

Since i have 2 observable lists, items and filtered I had to do this if, else. 由于我有2个可观察的列表,项目和过滤器,因此必须这样做。 Works well, I will see if it doesnt give me any bugs when I test it. 效果很好,我将在测试时查看它是否没有给我任何错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM