2

经过几次尝试和研究,我还没有设法从 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();

}

}

4

1 回答 1

1

问题是您永远不会改变窗格的可见性,因此永远无法到达您的听众。

试试这段代码:

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();

}
}

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

于 2013-07-26T09:02:37.850 回答