Stack Overflow Asked by Anuj Amin on December 20, 2021
Hi I’m currenntly doing a coding exercise where I create an application with 2 views. Create in it an application with two views. The first view should have a text field that’s used to ask for the user’s name. The second view then shows the user a greeting text. The greeting should be of the form "Welcome name!" where the user’s name is inserted in place of ‘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();
}
}
I tried converting input into a string via input.getText() and input.toString() but I have had no success.
Kindly note the following edit.
Label welcomeText = new Label();
The text of the label should only be set after receiving the input from the user.
Hence, you can create a welcomeText
Label and update its text value in the event handler using welcomeText.setText(input.getText())
.
Answered by Anuneet Anand on December 20, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP