javafx 如何从消息框中获取 return 值

javafx how to get return value from message box

我有一个问题,我无法获得 return 值,因为我想在控制器中使用它。关闭 window 后如何从复选框中获取 return 值。因为我需要控制器中的 return 值。谢谢

import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;

public class CheckBox {

  public static String display(String title, String message){
      Stage window = new Stage();
      String id = " ";

      window.initModality(Modality.APPLICATION_MODAL);
      window.setTitle(title);
      window.setMinWidth(250);

      Label label = new Label();
      label.setText(message);

      Button yButton = new Button("Y");
      Button nbButton = new Button("N");
      yButton.setId("Y");
      nbButton.setId("N");
      yButton.setOnAction(e -> window.close());
      nbButton.setOnAction(e -> window.close());

      VBox layout = new VBox(10);
      layout.getChildren().addAll(label,yButton, nbButton);
      layout.setAlignment(Pos.CENTER);
      Scene scene = new Scene(layout);
      window.setScene(scene);
      window.showAndWait();

      if(yButton.isPressed())
          return yButton.getId();

      else if(nbButton.isPressed())
          return nbButton.getId();

      return null;
  }
}

首先,我建议您不要使用与标准库中的名称匹配的名称。名称 CheckBox 不合适,因为它可以控制该名称。使用描述性的东西,比如 CheckBoxDialog.

避免使用静态上下文。在这种情况下,这是不必要的,并且显示出不好的风格。

这是一个通过保留您使用的静态方法实现的示例。

public class CheckBoxDialog {
    public static final String YES = "Y";
    public static final String NO = "N";

    private String exitCode = NO;

    private Stage window;
    private Label label;

    public CheckBoxDialog() {
        createGUI();
    }

    private void createGUI() {
        window = new Stage();
        window.initModality(Modality.APPLICATION_MODAL);
        window.setMinWidth(250);

        label = new Label();

        Button yButton = new Button(YES);
        Button nbButton = new Button(NO);

        yButton.setOnAction(e -> {
            exitCode = YES;
            window.close();
        });

        nbButton.setOnAction(e -> {
            exitCode = NO;
            window.close();
        });

        VBox layout = new VBox(10);
        layout.getChildren().addAll(label,yButton, nbButton);
        layout.setAlignment(Pos.CENTER);

        Scene scene = new Scene(layout);
        window.setScene(scene);
    }

    public void setTitle(String title) {
        window.setTitle(title);
    }

    public void setMessage(String message) {
        label.setText(message);
    }

    public String showAndWait() {
        window.showAndWait();
        return exitCode;
    }

    public static String display(String title, String message){
        CheckBoxDialog dlg = new CheckBoxDialog();
        dlg.setTitle(title);
        dlg.setMessage(message);

        return dlg.showAndWait();
    }
}