在 JavaFx 中,如何控制自定义控件的焦点?
In JavaFx, how to control focus of a custom control?
假设一个 JavaFX CustomControl
节点包含两个 TextField
s.
如果这些 TextField
中的任何一个有焦点,那么 CustomControl.isFocused()
应该 return true
。如果其中 none 个有焦点,那么 CustomControl.isFocused()
应该 return false
.
我该怎么做?
由于您的CustomControl
使用组合,您可以委托每个TextField
的焦点属性。给定两个实例,
private final TextField tf1 = new TextField("One");
private final TextField tf2 = new TextField("Two");
实例方法的实现isFocused()
就很简单了:
private boolean isFocused() {
return tf1.isFocused() | tf2.isFocused();
}
如图所示添加焦点侦听器here查看效果。
tf1.focusedProperty().addListener((Observable o) -> {
System.out.println(isFocused());
});
tf2.focusedProperty().addListener((Observable o) -> {
System.out.println(isFocused());
});
This can't be done. The whole problem is that isFocused()
is final
in Node
.
您似乎想覆盖 CustomControl
中的 isFocused()
,但这对于 final
方法是不可能的,并且它会违反具有焦点的单个组件的概念。由于 CustomControl
是一个组合,您需要在内部管理焦点。您可能想要使用自定义 FocusModel
,如 ListView
.
中所示
尝试一种解决方案:
public BooleanBinding aggregatedFocusProperty() {
return Bindings.or(field1.focusedProperty(), field2.focusedProperty());
}
现在在客户端你可以收听这个聚合焦点属性。
假设一个 JavaFX CustomControl
节点包含两个 TextField
s.
如果这些 TextField
中的任何一个有焦点,那么 CustomControl.isFocused()
应该 return true
。如果其中 none 个有焦点,那么 CustomControl.isFocused()
应该 return false
.
我该怎么做?
由于您的CustomControl
使用组合,您可以委托每个TextField
的焦点属性。给定两个实例,
private final TextField tf1 = new TextField("One");
private final TextField tf2 = new TextField("Two");
实例方法的实现isFocused()
就很简单了:
private boolean isFocused() {
return tf1.isFocused() | tf2.isFocused();
}
如图所示添加焦点侦听器here查看效果。
tf1.focusedProperty().addListener((Observable o) -> {
System.out.println(isFocused());
});
tf2.focusedProperty().addListener((Observable o) -> {
System.out.println(isFocused());
});
This can't be done. The whole problem is that
isFocused()
isfinal
inNode
.
您似乎想覆盖 CustomControl
中的 isFocused()
,但这对于 final
方法是不可能的,并且它会违反具有焦点的单个组件的概念。由于 CustomControl
是一个组合,您需要在内部管理焦点。您可能想要使用自定义 FocusModel
,如 ListView
.
尝试一种解决方案:
public BooleanBinding aggregatedFocusProperty() {
return Bindings.or(field1.focusedProperty(), field2.focusedProperty());
}
现在在客户端你可以收听这个聚合焦点属性。