如何以编程方式关闭对话框

时间:2016-11-28 13:56:54

标签: javafx

我需要一些帮助。我正在研究这个java fx项目。这个想法是为了防止默认的窗口关闭按钮行为,只有在登录成功时关闭对话框。

以下是我如何设置对话框并阻止对话框关闭的方法。

public class MainController extends Application implements Initializable{

// Create a dialog
private Dialog<Pair<String, String>> dialog = new Dialog<>();

/*Login resources*/
@FXML // fx:id="loginBtn"
private Button loginBtn; // Value injected by FXMLLoader

@FXML // fx:id="usernameTxt"
private TextField usernameTxt; // Value injected by FXMLLoader

@FXML // fx:id="loginProgressIndicator"
private ProgressIndicator loginProgressIndicator; // Value injected by FXMLLoader

@FXML // fx:id="passwordTxt"
private PasswordField passwordTxt; // Value injected by FXMLLoader

@FXML // fx:id="statusLbl"
private Label statusLbl; // Value injected by FXMLLoader

@FXML
void login(ActionEvent event) {

    Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();

    stage.fireEvent(
            new WindowEvent(
                    stage,
                    WindowEvent.WINDOW_CLOSE_REQUEST
            )
    );
}

/*Main Menu resources*/
@FXML // ResourceBundle that was given to the FXMLLoader
private ResourceBundle resources;

@FXML // URL location of the FXML file that was given to the FXMLLoader
private URL location;

@FXML // fx:id="visitBtn"
private Button visitBtn; // Value injected by FXMLLoader

@FXML // fx:id="reportBtn"
private Button reportBtn; // Value injected by FXMLLoader

@FXML // fx:id="setupBtn"
private Button setupBtn; // Value injected by FXMLLoader

@FXML
void report(ActionEvent event) {

}

@FXML
void setup(ActionEvent event) {

}

@FXML
void visit(ActionEvent event) {
    System.out.println("Visit Button Pressed.");
}

/**
 * The main entry point for all JavaFX applications.
 * The start method is called after the init method has returned,
 * and after the system is ready for the application to begin running.
 * <p>
 * <p>
 * NOTE: This method is called on the JavaFX Application Thread.
 * </p>
 *
 * @param primaryStage the primary stage for this application, onto which
 *                     the application scene can be set. The primary stage will be embedded in
 *                     the browser if the application was launched as an applet.
 *                     Applications may create other stages, if needed, but they will not be
 *                     primary stages and will not be embedded in the browser.
 */
@Override
public void start(Stage primaryStage) throws Exception {

    Parent root = FXMLLoader.load(getClass().getResource("main.fxml"));
    Scene scene = new Scene(root);

    primaryStage.setTitle("Main Menu - PEHCS Point of Sale");

    primaryStage.setScene(scene);
    primaryStage.show(); //This will display the main menu

    dialog.setTitle("Login - PEHCS Point of Sale");
    dialog.setHeaderText(null);


    // Get the Stage.
    Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
    // Add a custom icon.
    stage.getIcons().add(new Image(this.getClass().getResource("activa.jpg").toString()));


    /*This section prevents the dialog from closing when we press on the window X button*/
    Window window = dialog.getDialogPane().getScene().getWindow();
    window.setOnCloseRequest(new EventHandler<WindowEvent>() {

        /**
         * Invoked when a specific event of the type for which this handler is
         * registered happens.
         *
         * @param event the event which occurred
         */
        @Override
        public void handle(WindowEvent event) {
            event.consume();
        }
    });


    /*Set th content of that dialog to be the login.fxml resource file*/
    dialog.getDialogPane().setContent(FXMLLoader.load(getClass().getResource("login.fxml")));


    Optional<Pair<String, String>> result = dialog.showAndWait();

    result.ifPresent(usernamePassword -> {
        System.out.println("Username=" + usernamePassword.getKey() + ", Password=" + usernamePassword.getValue());
    });

}

/**
 * Called to initialize a controller after its root element has been
 * completely processed.
 *
 * @param location  The location used to resolve relative paths for the root object, or
 *                  <tt>null</tt> if the location is not known.
 * @param resources The resources used to localize the root object, or <tt>null</tt> if
 */
@Override
public void initialize(URL location, ResourceBundle resources) {
    assert visitBtn != null : "fx:id=\"visitBtn\" was not injected: check your FXML file 'main2.fxml'.";
    assert reportBtn != null : "fx:id=\"reportBtn\" was not injected: check your FXML file 'main2.fxml'.";
    assert setupBtn != null : "fx:id=\"setupBtn\" was not injected: check your FXML file 'main2.fxml'.";

    assert loginBtn != null : "fx:id=\"loginBtn\" was not injected: check your FXML file 'login.fxml'.";
    assert usernameTxt != null : "fx:id=\"usernameTxt\" was not injected: check your FXML file 'login.fxml'.";
    assert loginProgressIndicator != null : "fx:id=\"loginProgressIndicator\" was not injected: check your FXML file 'login.fxml'.";
    assert passwordTxt != null : "fx:id=\"passwordTxt\" was not injected: check your FXML file 'login.fxml'.";
    assert statusLbl != null : "fx:id=\"statusLbl\" was not injected: check your FXML file 'login.fxml'.";
}

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

窗口关闭事件正在on start方法中使用,并且它可以正常工作。现在我想在登录方法中关闭此对话框。这是我被困的地方。我需要帮助。

提前致谢。

1 个答案:

答案 0 :(得分:0)

要以编程方式关闭窗口,您只需要

@FXML
void login(ActionEvent event) {

    dialog.close();

}

请注意,这不会触发onCloseRequest处理程序,仅在外部请求关闭窗口时调用该处理程序(请参阅docs)。