问题描述
来自如何引用primaryStage 我了解到我可以得到 Stage
使用 control.getScene.getWindow()
,但是这将返回 Window
而不是 Stage
.我知道 Stage
是 Window
的一种,但是我的问题是返回的对象将始终是 Stage
还是其他的东西在某些情况下?另外,我是否会知道呢?
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?
推荐答案
JavaFX API中 Window
的子类是 Stage
和 PopupWindow
.反过来, PopupWindow
是 Popup
, ContextMenu
和 Tooltip
的超类,当然可以定义您的自己的子类.因此,设计一个情况很容易,其中 control.getScene().getWindow()
返回的内容不是 Stage
:
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);
}
}
如果您使用FXML,您可能不应该假定封闭的 Window
是 Stage
,因为您可能会想起将FXML用作 Popup 或其他非 Stage
Window
.
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.
这篇关于Scene.getWindow()始终是舞台吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!