有没有办法在没有事件处理程序的情况下等待按钮点击?

Is there any way to wait for button clicks without an EventHandler?

有什么方法可以在按下按钮 "ok" 时 return 某个整数,如果按下右上角的退出按钮则 return 另一个数字?

编辑: 这只是从更大的 class 中提取的方法。请假设 window 显示。我要的是确保任一两个数字的 return 的代码,但前提是按下按钮。


public static int showMessageDialog(String title, String object_message){
    stage = new Stage();
    stage.setMinHeight(150);
    stage.setMinWidth(250);
    stage.setTitle(title);

    ok = new Button("OK");

    gridPane = new GridPane();
    gridPane.setAlignment(Pos.CENTER);
    gridPane.setVgap(30);

    message = new Text(object_message);
    gridPane.addColumn(0, message, ok);
    scene = new Scene(gridPane);
    stage.setScene(scene);
    stage.show();
}

如果您想自己做,只需将 Stage 设为模态并使用 showAndWait 而不是 show 来阻止调用线程,直到 Stage关闭:

public static int showMessageDialog(String title, String object_message){
    stage = new Stage();
    stage.setMinHeight(150);
    stage.setMinWidth(250);
    stage.setTitle(title);
    stage.initModality(Modality.APPLICATION_MODAL);

    IntegerProperty returnCode = new SimpleIntegerProperty(-1);

    ok = new Button("OK");
    ok.setOnAction(ev -> {returnCode.set(1); stage.close();});

    gridPane = new GridPane();
    gridPane.setAlignment(Pos.CENTER);
    gridPane.setVgap(30);

    message = new Text(object_message);
    gridPane.addColumn(0, message, ok);
    scene = new Scene(gridPane);
    stage.setScene(scene);
    stage.showAndWait();

    return returnCode.get();
}