如何在新舞台弹出时禁用主要舞台

3
我有一个按钮,点击后会弹出新的窗口,但主窗口仍然可以被点击,如何禁用主窗口?
这是我的舞台和场景代码:
```html

stage和scene的代码如下:

```
private static final Stage stage = new Stage();
    private static final Stage newstage = new Stage();
    /**
     *
     */

    @Override
    public void start(Stage primaryStage) throws Exception {
      Parent root = FXMLLoader.load(getClass().getResource("MainMenu.fxml"));
      Scene scene = new Scene(root);
      scene.getStylesheets().addAll(this.getClass().getResource("background.css").toExternalForm());
      stage.setScene(scene);
      stage.show();
    }

     public void chgScene (String str) throws Exception {
       Parent root = FXMLLoader.load(getClass().getResource(str));
       Scene scene = new Scene(root);
       stage.setScene(scene);
       stage.show();
    }

    public void addStage (String str) throws Exception {
       Parent root = FXMLLoader.load(getClass().getResource(str));
       Scene scene = new Scene(root);
       newstage.setScene(scene);
       newstage.setResizable(false);
       newstage.showAndWait();
    }

    public void clearStage () {
        newstage.close();
    }

如果有任何错误,非常抱歉,因为我刚开始学习Java并需要为我的项目创建GUI界面。感谢您的帮助。

3个回答

7
你需要添加这个:

你需要添加以下内容:

 newstage.initModality(Modality.APPLICATION_MODAL);
 newstage.showAndWait();

see Modality


由于我的新舞台GUI包含一个处理此函数的按钮 public void clearStage () { newstage.close(); } 然后当我在主舞台上再次点击按钮时,出现了这个错误 无法在舞台可见后设置模态性 - Loong
@Loong 在调用 showAndWait 方法之前,您需要调用 initModality 方法。 - Kachna
1
在任何 Stage 实例上,你只能调用一次 initModality 方法。由于你在初始化程序中实例化了它并重复使用相同的实例,所以你应该在只执行一次的地方调用 initModality 方法,例如在 start() 方法中。此外,你也不应该将其设置为 static(这完全没有意义)。 - James_D
@Kachna 我通过使用 try 和 catch 来解决了 intiModality 函数的问题。 - Loong
@James_D 我使用静态(static)是因为我只是从另一个类中调用所有这些函数,如果我不使用静态(static),那么当我点击调用这个函数的按钮时它将不起作用。_clearStage()_。 - Loong
1
static的意思是字段属于类,而不属于类的实例。这与来自其他类的对象的可访问性无关,由publicprivate等控制。(在逻辑处理中使用try - catch结构也是错误的做法)。 - James_D

1
JavaFx有各种属性可供使用,只取决于开发者如何在逻辑上创造性地使用它们。
mainPane.setDisabled(true);
newPane.showAndWait();

0

请注意,initModality()在Linux平台运行时已经损坏了很长时间。

modal JavaFX stage initOwner prevents owner from resizing, bug?

是的,那篇帖子直接提到了initOwner(),但是调用initModality()似乎会触发这个bug。你可能会浪费很多时间尝试各种近似所需行为的修补方法,但似乎没有一种方法能够完全正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接