如何在Pane上获取JavaFX2.0可见性事件



经过几次尝试和研究,我还是没能从Pane中获得可见性事件。下面的示例似乎是我最好的尝试,但它不起作用。欢迎任何可行的提议。

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class VisibilityTestMain extends Application {
public static void main(String[] args) {
    VisibilityTestMain.launch(args);
}
@Override
public void start(Stage stage) throws Exception {
    Pane root = new Pane();
    ChangeListener<Boolean> visibilityListener = new ChangeListener<Boolean>() {
        @Override
        public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldValue, Boolean newValue) {
            System.out.println("####");
        }
    };
    root.visibleProperty().addListener(visibilityListener);
    Button button = new Button("Hello");
    button.setTranslateX(10);
    button.setTranslateY(20);
    root.getChildren().add(button);
    stage.setScene(new Scene(root, 50, 50));
    stage.show();
}

}

问题是您永远不会更改窗格的可见性,因此永远无法联系到您的侦听器。

请尝试以下代码:

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class VisibilityTestMain extends Application {
public static final Logger LOGGER = LoggerFactory.getLogger(VisibilityTestMain.class);
public static void main(String[] args) {
    VisibilityTestMain.launch(args);
}
@Override
public void start(Stage stage) throws Exception {
    final Pane root = new Pane();
    root.visibleProperty().addListener(new ChangeListener<Boolean>() {
        @Override
        public void changed(final ObservableValue<? extends Boolean> observableValue, final Boolean aBoolean, final Boolean aBoolean2) {
            System.out.println("####");
            //To change body of implemented methods use File | Settings | File Templates.
        }
    });
    Button button = new Button("Hello");
    button.setTranslateX(10);
    button.setTranslateY(20);
    root.getChildren().add(button);
    button.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(final ActionEvent actionEvent) {
            root.setVisible(false);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            root.setVisible(true);
        }
    });
    stage.setScene(new Scene(root, 50, 50));
    stage.show();
}
}

现在,您可以看到每次单击按钮时都会访问窗格的可见属性。

最新更新