JavaFX 文本区域中的 Tab 键导航

2022-09-03 09:27:16

如何使在文本区域中按 Tab 键导航到下一个控件?

我可以向 cath de 按键事件添加一个侦听器,但是如何使 te TextArea 控件失去焦点(不知道链中要聚焦的下一个字段)?

@FXML protected void handleTabKeyTextArea(KeyEvent event) {
    if (event.getCode() == KeyCode.TAB) {
        ...
    }
}

答案 1

我使用遍历方法

@Override
public void handle(KeyEvent event) {
    if (event.getCode().equals(KeyCode.TAB)) {
        Node node = (Node) event.getSource();
        if (node instanceof TextField) {
            TextFieldSkin skin = (TextFieldSkin) ((TextField)node).getSkin();
            if (event.isShiftDown()) {
                skin.getBehavior().traversePrevious();
            }
            else {
                skin.getBehavior().traverseNext();
            }               
        }
        else if (node instanceof TextArea) {
            TextAreaSkin skin = (TextAreaSkin) ((TextArea)node).getSkin();
            if (event.isShiftDown()) {
                skin.getBehavior().traversePrevious();
            }
            else {
                skin.getBehavior().traverseNext();
            }
        }

        event.consume();
    }
}

答案 2

如果按 TAB 键,则此代码遍历焦点;如果按 CONTROL+TAB,则插入 Tab 键

textArea.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent event) {
            if (event.getCode() == KeyCode.TAB) {
                SkinBase skin = (SkinBase) textArea.getSkin();
                if (skin.getBehavior() instanceof TextAreaBehavior) {
                    TextAreaBehavior behavior = (TextAreaBehavior) skin.getBehavior();
                    if (event.isControlDown()) {
                        behavior.callAction("InsertTab");
                    } else {
                        behavior.callAction("TraverseNext");
                    }
                    event.consume();
                }

            }
        }
    });

推荐