Reputation: 461
Here is my problem. I have a generic class called FilteredComboBox that extends 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).
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. Unfortunately when I say bookComboBox.getValue.getBookId I get cast exception, because getValue automatically calls toString method. 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.
Any ideas?
Upvotes: 0
Views: 3177
Reputation: 461
Yes it does extend ComboBox I solved my problem by doing his:
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. Works well, I will see if it doesnt give me any bugs when I test it.
Upvotes: 0
Reputation: 49185
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();
Upvotes: 1