简体   繁体   English

使用静态方法作为JavaFX更改侦听器

[英]Using static method as JavaFX change listener

Can someone explain to me why this isn't working? 有人可以向我解释为什么这不起作用?

public class ListenerTest {
    public static void addListener(Node node) {
        node.visibleProperty().addListener(ListenerTest::handleVisibleChanged);
    }

    private static void handleVisibleChanged(ObservableValue<? extends Boolean> observable,
            Boolean oldValue, Boolean newValue) {
        // Do something
    }
}

As you can see, I am using Java 8 method reference to assign a static method as a JavaFX change listener. 如您所见,我使用Java 8方法引用将静态方法指定为JavaFX更改侦听器。 It compiles just fine, but handleVisibleChanged() method is not invoked when visible property changes. 它编译得很好,但是当可见属性更改时不会调用handleVisibleChanged()方法。

Please don't offer workarounds or ask why am I doing this. 请不要提供解决方法或问我为什么要这样做。 Think of it as an exercise. 把它想象成一种练习。 :-) :-)

Here is a simple example that uses your two methods and works as expected: when the button is clicked, a message is printed. 下面是一个使用您的两种方法并按预期工作的简单示例:单击该按钮时,将打印一条消息。

public class ListenerTest extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Label label = new Label("You can see me");
        addListener(label);
        Button button = new Button("Hide/Show");
        button.setOnAction(e -> label.setVisible(!label.isVisible()));

        Scene scene = new Scene(new VBox(20, label, button));
        stage.setScene(scene);
        stage.show();
    }
    public static void addListener(Node node) {
        node.visibleProperty().addListener(ListenerTest::handleVisibleChanged);
    }
    private static void handleVisibleChanged(ObservableValue<?> a, Boolean b, Boolean newValue) {
        System.out.println("new value: " + newValue);
    }

    public static void main(String[] args) {
        launch();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM