Java 无法将文本字段转换为字符串
嗨,我现在正在做一个编码练习,在这里我创建了一个有两个视图的应用程序。在其中创建一个具有两个视图的应用程序。第一个视图应该有一个用于询问用户名的文本字段。然后,第二个视图向用户显示问候语文本。问候语的形式应为“欢迎姓名!”,其中插入用户名以代替“姓名”Java 无法将文本字段转换为字符串,java,user-interface,javafx,scene,Java,User Interface,Javafx,Scene,嗨,我现在正在做一个编码练习,在这里我创建了一个有两个视图的应用程序。在其中创建一个具有两个视图的应用程序。第一个视图应该有一个用于询问用户名的文本字段。然后,第二个视图向用户显示问候语文本。问候语的形式应为“欢迎姓名!”,其中插入用户名以代替“姓名” package application; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class GreeterApplication extends Application {
public static void main(String[] args) {
launch(GreeterApplication.class);
}
@Override
public void start(Stage window) throws Exception {
//1. Creating the view
//1.1 Creating components to be used
Label intro = new Label("Enter your name and start.");
Button start = new Button("start");
TextField input = new TextField();
//1.2 creating new layout
GridPane layout = new GridPane();
layout.add(intro, 0, 0);
layout.add(input, 0, 1);
layout.add(start, 0, 2);
// 1.3 Styling the layout
//1.4 creating view itself and setting it to use the layout
Scene first = new Scene(layout);
//2. Creating new view
StackPane welcome = new StackPane();
String name = input.getText();
Label welcomeText = new Label("Welcome " + input + "!"); //inpu
welcome.getChildren().add(welcomeText);
Scene welcomeView = new Scene(welcome);
//3. Adding event handler
start.setOnAction((event) -> {
if (!input.getText().isEmpty()) {
window.setScene(welcomeView);
}
});
window.setScene(first);
window.show();
}
}
我尝试通过input.getText()和input.toString()将输入转换为字符串,但没有成功。请注意以下编辑。
Label-welcomeText=new-Label()代码>
标签文本只能在收到用户输入后设置。
因此,您可以创建一个welcomeText
标签,并在事件处理程序中使用welcomeText.setText(input.getText())
更新其文本值。您得到了什么错误或异常?您在用户有机会键入任何内容之前设置了标签的文本。在事件处理程序中设置文本(并使用input.getText()
)。我知道了,就像James说的那样。我没有收到错误,只是没有打印任何内容。