Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force JavaFX ComboBox to loose focus?

I would like that my JavaFX ComboBox looses the focus after a selection. Any ideas?

like image 940
IBACK Avatar asked Dec 13 '25 17:12

IBACK


1 Answers

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);
});
like image 120
kleopatra Avatar answered Dec 16 '25 06:12

kleopatra