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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With