公共API中没有访问JavaFX中属性的侦听器列表的机制。
我不确定我真的看到这个需求。你的代码可以控制添加和删除监听器的时间,所以当添加监听器时你基本上总是“知道”。从更广泛的意义上讲,您的用户界面或用户界面组件始终是某种形式数据的呈现形式,因此,是否注册监听器只是这些数据的功能。
对于一个具体的例子,考虑使用的情况下在评论中引用:
public class CustomComponent extends BorderPane {
private final Button button = new Button("Button");
private final TextField textField = new TextField();
private final ObjectProperty<Orientation> orientation = new SimpleObjectProperty<>();
public ObjectProperty<Orientation> orientationProperty() {
return orientation ;
}
public final Orientation getOrientation() {
return orientationProperty().get();
}
public final void setOrientation(Orientation orientation) {
orientationProperty().set(orientation);
}
public CustomControl(Orientation orientation) {
setCenter(textField);
ChangeListener<Number> widthBindingListener = (obs, oldWidth, newWidth) ->
button.setPrefWidth(newWidth.doubleValue());
orientationProperty().addListener((obs, oldOrientation, newOrientation) -> {
if (newOrientation == Orientation.HORIZONTAL) {
textField.widthProperty().removeListener(widthBindingListener);
button.setPrefWidth(Control.USE_COMPUTED_SIZE);
setTop(null);
setLeft(button);
} else {
textField.widthProperty().addListener(widthBindingListener);
button.setPrefWidth(textField.getWidth());
setLeft(null);
setTop(button);
}
}
setOrientation(orientation);
}
public CustomControl() {
this(Orientation.VERTICAL);
}
// other methods etc....
}
在这个例子中,你可能只需要使用一个结合,而不是听众:
button.prefWidthProperty().bind(Bindings
.when(orientationProperty().isEqualTo(Orientation.HORIZONTAL))
.then(Control.USE_COMPUTED_SIZE)
.otherwise(textField.widthProperty()));
但没有证明这个概念......
请注意,正如在@Clemens评论中一样,您可以始终确保一个听众只用一次成语注册一次:
textField.widthProperty().removeListener(widthBindingListener);
textField.widthProperty().addListener(widthBindingListener);
但是这只是在我看来不是非常好的做法:removeListener
涉及迭代通过侦听器列表中(和在它尚未加入的情况下,听众的整个列表)。这种迭代是不必要的,因为信息已经在其他地方可用。
AFAIK无法访问JavaFX中的用户。你能举个例子说明你为什么需要他们(或者认为你是这样做的)?我从来没有遇到需要这样做。 –
正如我在我的问题中提到的,我试图避免多次注册与侦听器相同的对象。一个可能发生这种情况的用例会在附加评论中出现,但请相信我有可能,并且当它发生时,事件被触发到侦听器的次数与侦听器出现在事件侦听器列表中的次数相同。效率低下,不必要,因为听众几乎总是(99.9999999%的时间)需要处理事件 – jfr
是的,我明白:我从来没有遇到过你不知道听众是否已经注册的情况。这是我想知道的用例。 –