如何解决buttonclick后返回文本字段
我正在尝试将字符串从一个屏幕移动到另一个屏幕。 程序启动后,我将创建一个带有按钮的场景。 单击此按钮,我将创建一个带有textField和按钮的新场景。 我希望该程序返回用户单击第二个按钮后在文本字段中写入的内容。 我试图将其放在Lambada的第二个按钮中,但这没用
( 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);
GridPane.setConstraints(tekstField,1);
GridPane.setConstraints(button,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.showAndWait()
代替window.show()
,它将阻塞执行,直到关闭窗口为止,以达到所需的结果。请注意,目前没有真正的理由为此设置变量,您只需在文本字段中查找值即可:
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);
GridPane.setConstraints(tekstField,1);
GridPane.setConstraints(button,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以及相关的类,例如Dialog
和Alert
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。