gpt4 book ai didi

java - PrimaryStage 无法解析为变量 :, 在其他类中使用时:JavaFX

转载 作者:行者123 更新时间:2023-11-30 05:21:37 25 4
gpt4 key购买 nike

我知道有很多与此特定错误相关的问题,但我找不到适合我的错误的解决方案。

所以我正在做的是创建一个 javaFX 应用程序并使用 Modality 库,以便我可以创建一个始终在主舞台上方打开的子窗口。但是我收到的错误是,由于 PrimaryStageScope 问题,我无法在 initOwner() 函数内设置 PrimaryStage 变量在 SubModal 类的范围之外。

让我写一些代码来让事情变得清楚..

//SubModal Class
class SubModal extends singleModal {

SubModal()
{
Stage subStage1 = new Stage();
subStage1.setTitle("New Stage1");
FlowPane root = new FlowPane();
root.setAlignment(Pos.CENTER);
Scene scene1 = new Scene(root, 300, 200);
Button btn2 = new Button("Button: Stage1");
root.getChildren().add(btn2);
btn2.setOnAction(eve-> System.out.println("Clicked on Stage 1 Button"));
subStage1.initOwner(primaryStage);
subStage1.initModality(Modality.NONE);
subStage1.setScene(scene1);
subStage1.show();
}
}

//SingleModal Class
public class singleModal extends Application {

public static void main(String[] args) {

Application.launch(args);
}

public void start(Stage primaryStage) {

primaryStage.setTitle("PrimaryStage");

FlowPane root = new FlowPane();
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 700, 200);
Button btn = new Button("Open New Stage");
btn.setOnAction(eve-> new NewStage());
root.getChildren().add(btn);
primaryStage.setScene(scene);
primaryStage.show();
}
}

从上面的代码..

subStage1.initOwner(primaryStage);

该特定行显示错误

primaryStage cannot be resolved to a variable

我知道这是因为 PrimaryStage() 在 subModal 类中不可用。

所以我的问题是如何在 JavaFX 中解决这个问题。如何在 SubModal 类中引入 primaryStage 值,以便我可以运行此 Code ErrorFree

最佳答案

对于所需的功能(“创建一个始终在主阶段上方打开的子窗口”),无需扩展 singleModal
这是一个mre演示它:

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Modality;
import javafx.stage.Stage;

public class SingleModal extends Application {

@Override
public void start(Stage primaryStage) {

Stage subStage1 = new Stage();
subStage1.setTitle("New Stage1");

Button btn2 = new Button("Button: Stage1");
FlowPane root2 = new FlowPane();
root2.setAlignment(Pos.CENTER);
root2.getChildren().add(btn2);
btn2.setOnAction(eve-> System.out.println("Clicked on Stage 1 Button"));
subStage1.initOwner(primaryStage);
subStage1.initModality(Modality.NONE);
Scene scene1 = new Scene(root2, 300, 200);
subStage1.setScene(scene1);

primaryStage.setTitle("PrimaryStage");
FlowPane root = new FlowPane();
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 700, 200);
Button btn = new Button("Open New Stage");
btn.setOnAction(eve-> subStage1.show());
root.getChildren().add(btn);
primaryStage.setScene(scene);
primaryStage.show();
}

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

关于java - PrimaryStage 无法解析为变量 :, 在其他类中使用时:JavaFX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59478733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com