JavaFX ListView键盘导航功能

时间:2016-03-14 13:12:25

标签: java user-interface javafx

我对JavafX的GUI元素非常满意,但是,ListView控件(https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ListView.html)默认情况下似乎没有提供“常用”键盘导航功能。

我可以使用箭头键上下移动,但是我不能通过按下任意键跳转到以“a”开头的项目。

虽然可以轻松添加此功能,但我想知道它是否可能是内置的?

1 个答案:

答案 0 :(得分:3)

我是这样实现的:

private String searchText = "";
private long searchTextLastTyped = 0;
private int searchTextSkip = 0;

...

listView.setOnKeyTyped(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent event) {
        if (event.getCharacter() != null) {
            //in case of same character typed more times = search next occurence
            if (searchText.equals(event.getCharacter())) {
                searchTextSkip++;
            } else {
                //in case typing more characters relatively quickly = append character
                if (System.currentTimeMillis() - searchTextLastTyped < 1000) {
                    searchText += event.getCharacter();
                //typing new character after pause = new search
                } else {
                    searchText = event.getCharacter();
                }
            }
            searchTextLastTyped = System.currentTimeMillis();

            boolean found = false;
            int skipped = 0;
            for (T item : getItems()) {
                if (getTextValue(item).toUpperCase().startsWith(searchText.toUpperCase())) {
                    if (searchTextSkip > skipped) {
                        skipped++;
                        continue;
                    }
                    setValue(item);
                    found = true;
                    break;
                }
            }

            //reset to first occurence
            if (!found) {
                searchTextSkip = 0;
            }
        }
    }
});