Tab key navigation in JavaFX TextArea

后端 未结 6 1439
暖寄归人
暖寄归人 2021-02-02 16:47

How do I make hitting the Tab Key in TextArea navigates to the next control ?

I could add a listener to cath de key pressed event, but how do I make te TextArea control

6条回答
  •  借酒劲吻你
    2021-02-02 17:07

    Inspired by the previous answers and for a very similar case, I built the following class:

    /**
     * Handles tab/shift-tab keystrokes to navigate to other fields,
     * ctrl-tab to insert a tab character in the text area.
     */
    public class TabTraversalEventHandler implements EventHandler {
        @Override
        public void handle(KeyEvent event) {
            if (event.getCode().equals(KeyCode.TAB)) {
                Node node = (Node) event.getSource();
                if (node instanceof TextArea) {
                    TextAreaSkin skin = (TextAreaSkin) ((TextArea)node).getSkin();
                    if (!event.isControlDown()) {
                        // Tab or shift-tab => navigational action
                        if (event.isShiftDown()) {
                            skin.getBehavior().traversePrevious();
                        } else {
                            skin.getBehavior().traverseNext();
                        }
                    } else {
                        // Ctrl-Tab => insert a tab character in the text area
                        TextArea textArea = (TextArea) node;
                        textArea.replaceSelection("\t");
                    }
                    event.consume();
                }
            }
        }
    }
    

    I just have not seen the necessity of handling tab in the context of a TextField so I removed this part.

    Then this class can be very easily used as described by User:

    TextArea myTextArea = new TextArea();
    mytTextArea.addEventFilter(KeyEvent.KEY_PRESSED, new TabTraversalEventHandler());
    

    And the whole thing works like a charm :)

提交回复
热议问题