没有EventHandler,有没有办法等待按钮点击?

时间:2015-04-16 09:33:59

标签: java button javafx int return

当按下“ok”按钮时,有什么方法可以返回某个整数,如果按下右上角的退出按钮,还会返回另一个数字吗?

编辑:这只是一个从更大的类中取出的方法。请假设窗口显示。我要求的是确保两个数字返回的代码,但仅当按下按钮时才会这样。


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();
}

1 个答案:

答案 0 :(得分:0)

如果你想自己动手,只需制作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();
}