Reputation: 3855
I am trying to make a ComboBox which has a functionality of search a match from its items.
Here is a code sample of what I have done,
ObservableList<String> ab = FXCollections.observableArrayList("z", "asxdf", "abasdf", "bcasdf", "b", "bc", "bcd", "c");
final ComboBox box = new ComboBox(ab);
box.setEditable(true);
box.setOnKeyReleased(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent t) {
box.show();
for (String item : items) {
if (item.startsWith(box.getEditor().getText())) {
box.getSelectionModel().select(item); //which selects the item.
break;
}
}
}
});
Now the problem is box.getSelectionModel().select(item);
selects that specific item which is typed in the ComboBox, but I don't want to select that item, I just want to hover on (focus on) that item like when mouse hovers.
Can anyone tell me the code to replace with box.getSelectionModel().select(item);
and help me solve this problem.
Upvotes: 1
Views: 4195
Reputation: 21
to reply late, but I only faced that issue today after I migrated a hole application from Swing to FX. I am using Java 8. (still)
This is how I made it work. Hope it is will help in case someone still has this issue.
public class MyComboBox extends ComboBox<String> {
public EditorComboBox() {
// this event is created when the internal listView is displayed
setOnShowing(event -> {
ComboBoxListViewSkin<?> skin = (ComboBoxListViewSkin<?>)getSkin();
if (skin != null) {
((ListView<?>) skin.getPopupContent()).scrollTo(getSelectionModel().getSelectedIndex());
}
});
}
}
Upvotes: 2
Reputation: 10892
You can get the ListView from the ComboBox by this code:
ListView<?> lv = ((ComboBoxListViewSkin) getSkin()).getListView();
Then you can focus to the item:
lv.getFocusModel().focus(N);
or just scroll to it:
lv.scrollTo(N)
Upvotes: 6