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. It compiles just fine, but handleVisibleChanged() method is not invoked when visible property changes.
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.