我试图通过单击按钮来打开一个舞台,但在打开它之前,我想检查该舞台是否已经打开,然后将打开的舞台弹出到前面,而不是打开一个新的舞台(没有多重打开)同一阶段)。
@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
的引用并继续使用该引用。
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
保留在内存中,那么您可以稍微更改上面的内容。
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();
}
}
}
您可能还想存储对已加载 Controller 的引用,具体取决于您的需要。
关于java - 在再次打开之前检查阶段是否已经打开 javafx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52693199/