我希望我的JavaFX
ComboBox
在选中后失去焦点。有什么想法吗?ComboBox
在选中后失去焦点。有什么想法吗?不幸的是,javafx没有公共api,可以以编程方式从一个节点中将焦点转移离开。作为解决方法——正如James_D所建议的那样——就是明确要求将焦点转移到另一个节点:
node.requestFocus();
这样做意味着调用代码知道节点(在OP的上下文中似乎是这种情况)。
实际上,Scene 上有提供所需功能的 API。缺点是:它是 package private 的,需要使用 com.sun.xx 层次结构中的 Direction 类。因此,如果你愿意(并且被允许)冒险,另一种选择是通过反射调用该 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);
});