Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tab key navigation in JavaFX TextArea

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 to lose it focus (without knowing the next field in the chain to be focused) ?

@FXML protected void handleTabKeyTextArea(KeyEvent event) {
    if (event.getCode() == KeyCode.TAB) {
        ...
    }
}
like image 640
nailujed Avatar asked Oct 12 '12 13:10

nailujed


2 Answers

I use the traverse-methods

@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();
    }
}
like image 138
Tom Avatar answered Sep 22 '22 07:09

Tom


This code traverse focus if pressing TAB and insert tab if pressing CONTROL+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();
                }

            }
        }
    });
like image 44
amru Avatar answered Sep 23 '22 07:09

amru