无法将文本字段转换为字符串

Cannot convert textfield into string

您好,我目前正在做一个编码练习,我在其中创建了一个具有 2 个视图的应用程序。在其中创建一个具有两个视图的应用程序。第一个视图应该有一个用于询问用户姓名的文本字段。第二个视图然后向用户显示问候文本。问候语应采用“欢迎姓名!”的形式。插入用户名代替 'name'.


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()).

在事件处理程序中更新其文本值