单击按钮后返回文本字段

Returning textfield after buttonclick

我正在尝试将字符串从一个屏幕移动到另一个屏幕。

程序启动后,我会创建一个带有按钮的屏幕。

单击此按钮我创建了一个带有文本字段和按钮的新屏幕。

我希望程序 return 用户在单击第二个按钮后在文本字段中写入的内容。

我试图将它放在第二个按钮 lambda 中,但那没有用

( e -> {
            String name= ConfirmBox.register();
            return name;
        });

我注意到的第二件事是在我的第一个按钮 actionListener

button.setOnAction(e -> {
        String string= ConfirmBox.register();
        System.out.print(string);   
    });

按下第一个按钮后,输出为空。我猜这是因为 return 太快了,但是我如何减慢它的速度以便在用户按下按钮后得到正确的 return?

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setTitle("titel");
        button = new Button("button");
        
        button.setOnAction(e -> {
            String string= ConfirmBox.register();
            System.out.print(string);   
        });
     }


 public class ConfirmBox {
     static String save; 

public static String register() {

    Stage window = new Stage();
    
    window.initModality(Modality.APPLICATION_MODAL);
    window.setTitle("title");
    
    Label label = new Label("enter tekst");
    TextField tekstField = new TextField();
    Button button = new Button("ok");
    
    
    
    button.setOnAction(e-> 
    {
        /*
        String name= ConfirmBox.register();
        return name;
        */

    save  = tekstField.getText();
    window.close();
    });

    GridPane layout = new GridPane();
    GridPane.setConstraints(label, 0, 0);
    GridPane.setConstraints(tekstField, 0, 1);
    GridPane.setConstraints(button, 0, 2);
        
    layout.getChildren().addAll(label, tekstField, button);
    Scene scene = new Scene (layout, 300, 250);
    window.setScene(scene);
    window.show();

    return save;
        
    }   
}

你是正确的 return 语句基本上是立即执行的,所以在用户按下按钮之前,导致 String save 被设置。

而不是window.show(),使用window.showAndWait(),这将阻塞执行直到window关闭,达到预期的结果。请注意,此时没有真正的理由为此设置变量,您可以在文本字段中查找值:

public class ConfirmBox {

    public static String register() {
    
        Stage window = new Stage();
        
        window.initModality(Modality.APPLICATION_MODAL);
        window.setTitle("title");
        
        Label label = new Label("enter tekst");
        TextField tekstField = new TextField();
        Button button = new Button("ok");
        
        
        
        button.setOnAction(e -> window.close());
    
        GridPane layout = new GridPane();
        GridPane.setConstraints(label, 0, 0);
        GridPane.setConstraints(tekstField, 0, 1);
        GridPane.setConstraints(button, 0, 2);
            
        layout.getChildren().addAll(label, tekstField, button);
        Scene scene = new Scene (layout, 300, 250);
        window.setScene(scene);
        
        //window.show();
 
        window.showAndWait();
    
        return tekstField.getText();
        
    }   
}

在这里值得一提的是,您在某种程度上是在重新发明轮子。查看 TextInputDialog class,以及相关的 类,例如 DialogAlert