我希望我的 JavaFX ComboBox
在选择后失去焦点。有什么想法吗?
最佳答案
不幸的是,javafx 没有公共(public) api 以编程方式将焦点从节点转移。解决方法 - 正如 James_D 所建议的那样- 是明确请求焦点到另一个节点上:
node.requestFocus();
这样做意味着调用代码知道该节点(在 OP 的上下文中似乎就是这种情况)。
实际上,是 Scene 上的 api 提供了所需的功能。缺点:它是包私有(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);
});
关于java - 如何强制 JavaFX ComboBox 失去焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32069107/