How do I restrict keyboard focus to controls within a Node?

javafx-2

Solution

For: 1) 3 alternative suggestions, a- Add a key event handler to the dialogbox pane to catch the Tab key pressings

dialogbox.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {

    @Override
    public void handle(javafx.scene.input.KeyEvent event) {
        if (event.getCode() == KeyCode.TAB) {
            System.out.println("TAB pressed");
            event.consume(); // do nothing
        }
    }
});

b- Temporarily disable all children of the main `StackPane` except the lastly added dialogbox child.

// Assuming dialogbox is at last in the children list
for(int i=0; i<mainPane.getChildren().size()-1; i++){
     // Disabling will propagate to sub children recursively
    mainPane.getChildren().get(i).setDisable(true);
}

c- Same as b but manually disable focusing to controls by `node.setFocusTraversable(false)` (spot kick). Surely this will not be your choice..

2) Tell the dialogbox which node should take the focus after the dialog is shown (through constructor or setter method).

// init dialogbox and show it then
dialogbox.setFocusTo(node_in_dialogbox);

Problem

I'm trying to implement a reusable method for displaying a node as a lightweight dialog. The node is added to the top of a StackPane while the background is then blurred. There are 2 problems: 1) Controls in the background node of the stackpane are still able to receive focus. 2) How do I give focus to the top-level node. I know there is a requestFocus method on Node, but I need to give it to a control nested within the node. Since this is intended to be a reusable method, I can't reference the controls directly. (if I can sidestep the whole problem by finding an existing implementation, that would be best, but I haven't found a 3rd party solution yet) Thanks

Original source