Is Scene.getWindow() Always a Stage?

折月煮酒 提交于 2019-12-13 06:18:45

问题


Coming from How to reference primaryStage I learned that I can get the Stage of a particular control by using control.getScene.getWindow(), but this returns a Window instead of a Stage. I know that Stage is a type of Window, but my question is will the returned object always be a Stage, or will it be something else in some cases? Also, will I know that it will be something else?


回答1:


The subclasses of Window in the JavaFX API are Stage and PopupWindow. PopupWindow in turn is a superclass of Popup, ContextMenu, and Tooltip, and of course it's possible to define your own subclasses. So it's reasonably easy to design a case where control.getScene().getWindow() returns something that is not a Stage:

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.stage.Window;

public class ContextMenuExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        StackPane root = new StackPane();
        Label label = new Label("Right click here");
        root.getChildren().add(label);

        ContextMenu contextMenu = new ContextMenu();
        MenuItem menuItem = new MenuItem();
        contextMenu.getItems().add(menuItem);

        final Button button = new Button("Click Me");
        menuItem.setGraphic(button);
        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                Window window = button.getScene().getWindow();
                System.out.println("window is a stage: "+(window instanceof Stage));
            }
        });
        label.setContextMenu(contextMenu);
        Scene scene = new Scene(root, 250, 100);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

If you use FXML, you probably shouldn't assume that your enclosing Window is a Stage as you might conceivably re-use the FXML as the content of a Popup, or other non-Stage Window, in the future.



来源:https://stackoverflow.com/questions/25095578/is-scene-getwindow-always-a-stage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!