Tab key navigation in JavaFX TextArea

后端 未结 6 1436
暖寄归人
暖寄归人 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

    As of Java 9 (2017), most answers in this page don't work, since you can't do skin.getBehavior() anymore.

    This works:

    @Override
    public void handle(KeyEvent event) {
        KeyCode code = event.getCode();
    
        if (code == KeyCode.TAB && !event.isShiftDown() && !event.isControlDown()) {
            event.consume();
            Node node = (Node) event.getSource();
            try {
                Robot robot = new Robot();
                robot.keyPress(KeyCode.CONTROL.getCode());
                robot.keyPress(KeyCode.TAB.getCode());
                robot.delay(10);
                robot.keyRelease(KeyCode.TAB.getCode());
                robot.keyRelease(KeyCode.CONTROL.getCode());
                }
            catch (AWTException e) { }
            }
        }
    

    This also works:

    @Override
    public void handle(KeyEvent event) {
        KeyCode code = event.getCode();
    
        if (code == KeyCode.TAB && !event.isShiftDown() && !event.isControlDown()) {
            event.consume();
            Node node = (Node) event.getSource();            
            KeyEvent newEvent 
              = new KeyEvent(event.getSource(),
                         event.getTarget(), event.getEventType(),
                         event.getCharacter(), event.getText(),
                         event.getCode(), event.isShiftDown(),
                         true, event.isAltDown(),
                         event.isMetaDown());
    
            node.fireEvent(newEvent);            
            }
        }
    

    Both simulate pressing CTRL+TAB when the user presses TAB. The default behaviour of the TextArea for CTRL+TAB is moving the focus to the next control. Please note the second code is based on Johan De Schutter's answer.

提交回复
热议问题