在再次打开阶段之前,请检查阶段是否已经打开 [英] Check if a stage is already open before open it again javafx

查看:62
本文介绍了在再次打开阶段之前,请检查阶段是否已经打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过单击一个按钮来打开一个舞台,但是在打开它之前,我想检查该舞台是否已经打开,然后将打开的舞台弹出到最前面,而不是打开一个新的舞台(不进行多次打开)同一阶段).

I'm trying to open a stage by clicking a button, but before opening it, I want to check if the stage is already opened, then popup the opened stage to the front instead of opening a new one(no multi open of the same Stage).

@FXML
private void btn_Validate(ActionEvent event) {

    try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/scontrols/students/StudentManagement.fxml"));
        Parent root = (Parent) loader.load();

        StudentManagementController sendTo =  loader.getController();
        sendTo.receiveFromCamera(txtPictureName.getText());
        Stage stage = new Stage();
        stage.setScene(new Scene(root));
         if(!stage.isShowing())
         {
             stage.show();}

    } catch (IOException ex) {
        Logger.getLogger(WebCamController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

推荐答案

您正在检查新创建的 Stage上的!stage.isShowing().这将永远不会做您想要的.您需要保留对另一个Stage的引用,并继续使用该引用.

You're checking !stage.isShowing() on the newly created Stage. This will never do what you want. You need to keep a reference to the other Stage and keep using that reference.

public class Controller {

  private Stage otherStage;

  @FXML
  private void btn_Validate(ActionEvent event) {
    if (otherStage == null) {
      Parent root = ...;

      otherStage = new Stage();
      otherStage.setScene(new Scene(root));
      otherStage.show();

    } else if (otherStage.isShowing()) {
      otherStage.toFront();
    } else {
      otherStage.show();
    }
  }
}

如果您不想在Stage关闭时将其保留在内存中,则可以稍作改动.

If you don't want to keep the Stage in memory when it's closed, then you can alter the above slightly.

public class Controller {

  private Stage otherStage;

  @FXML
  private void btn_Validate(ActionEvent event) {
    if (otherStage == null) {
      Parent root = ...;

      otherStage = new Stage();

      otherStage.setOnHiding(we -> otherStage = null);

      otherStage.setScene(new Scene(root));
      otherStage.show();

    } else {
      otherStage.toFront();
    }
  }
}

您可能还需要存储对加载的控制器的引用,具体取决于您的需求.

You may want to store a reference to the loaded controller as well, depending on your needs.

这篇关于在再次打开阶段之前,请检查阶段是否已经打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆