【发布时间】:2020-10-05 19:44:15
【问题描述】:
我正在尝试将字符串从一个屏幕移动到另一个屏幕。
程序启动后,我会创建一个带有按钮的屏幕。
单击此按钮我创建了一个带有文本字段和按钮的新屏幕。
我希望程序在用户单击第二个按钮后返回用户在文本字段中写入的内容。
我试图把它放在第二个按钮 lambda 中,但是没有用
( e -> {
String name= ConfirmBox.register();
return name;
});
我注意到的第二件事是在我的第一个按钮 actionListener 中
button.setOnAction(e -> {
String string= ConfirmBox.register();
System.out.print(string);
});
一旦我按下第一个按钮,我就会得到空输出。我猜这是因为返回速度太快了,但是如何减慢速度,以便在用户按下按钮后获得正确的返回?
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;
}
}
【问题讨论】:
-
您使用属于 Swing 的 JFrame 标记了问题,但您的 cvode 看起来您正在使用 JavaFX。
-
正确。我现在改了
-
我想如果你把
window.show()改成window.showAndWait()就行了。