Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus on next item in container

Is there a way to programmatically focus on the next focusable node in a container without directly calling on a specific component's requestFocus() method? This functionality would be similar to pressing the tab button to traverse focus between components where disabled nodes are skipped.

like image 359
David Yee Avatar asked May 01 '15 08:05

David Yee


2 Answers

There is no public method for this. Only hacks and workarounds.

You could use the node's

impl_traverse(Direction.NEXT);

method. But this one is deprecated and could be removed at any time and your code breaks with a new java version.

Alternatively you could catch the enter key and fire a tab key event. But that's equally ugly.

Or if you are in a textfield you could do it like this:

if( textfield.getSkin() instanceof BehaviorSkinBase) {
    ((BehaviorSkinBase) textfield.getSkin()).getBehavior().traverseNext();  
}

But that's also discouraged since it isn't api.

And even if you'd use reflection to access the scene's traverse method like this:

Method[] allMethods = scene.getClass().getDeclaredMethods();
for (Method m : allMethods) {
    String mname = m.getName();
    if (mname.startsWith("traverse")) {
        m.setAccessible(true);
        m.invoke(scene, new Object[] { textfield, Direction.NEXT });
    }
}

you'd end up with having to provide a Direction parameter which is also discouraged.

The best thing you can do is to comment and vote on this issue.

like image 169
Roland Avatar answered Nov 14 '22 20:11

Roland


According to your use case, you may also filter and convert Enter keys to Tab on parent pane:

@Override
public void start( final Stage primaryStage )
{
    TextField field1 = new TextField();
    TextField field2 = new TextField();
    TextField field3 = new TextField();
    VBox vbox = new VBox( field1, field2, field3 );

    vbox.addEventFilter( KeyEvent.KEY_PRESSED, ( KeyEvent event ) ->
    {
        if ( event.getCode() == KeyCode.ENTER )
        {
            KeyEvent newEvent
                    = new KeyEvent(
                            null,
                            null,
                            KeyEvent.KEY_PRESSED,
                            "",
                            "\t",
                            KeyCode.TAB,
                            event.isShiftDown(),
                            event.isControlDown(),
                            event.isAltDown(),
                            event.isMetaDown()
                    );

            Event.fireEvent( event.getTarget(), newEvent );
            event.consume();
        }
    } );
    final Scene scene = new Scene( vbox, 800, 600 );
    primaryStage.setScene( scene );
    primaryStage.show();

}
like image 4
Uluk Biy Avatar answered Nov 14 '22 20:11

Uluk Biy