I would like that my JavaFX ComboBox looses the focus after a selection. Any ideas?
Unfortunately, javafx has no public api to programmatically transfer focus away from a node. A workaround - as suggested by James_D - is to explicitly request the focus onto another node:
node.requestFocus();
Doing so implies that the calling code knows that node (which seems to be the case in OP's context).
Actually, there is api on Scene that provides the needed functionality. The down-side: it's package private and requires usage of the class Direction in the com.sun.xx hierarchy. So if you are willing (and allowed) to take the risk an alternative is to reflectively invoke that api:
/**
* Utility method to transfer focus from the given node into the
* direction. Implemented to reflectively (!) invoke Scene's
* package-private method traverse.
*
* @param node
* @param next
*/
public static void traverse(Node node, Direction dir) {
Scene scene = node.getScene();
if (scene == null) return;
try {
Method method = Scene.class.getDeclaredMethod("traverse",
Node.class, Direction.class);
method.setAccessible(true);
method.invoke(scene, node, dir);
} catch (NoSuchMethodException | SecurityException
| IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
}
// usage, f.i. on change of selection of a comboBox
combo.getSelectionModel().selectedItemProperty().addListener((source, ov, nv) -> {
traverse(combo, Direction.NEXT);
});
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