Brian Smith Brian Smith - 1 month ago 13
Java Question

JavaFX UI elements not showing up in Stage

I am making a basic JavaFx program. The program displays text and a button in the first scene and when clicking the button the program navigates to another scene. The code runs fine but there is no button or text showing up in the window. Can anyone suggest why this is happening? Any input would be much appreciate. Full program below:

import javafx.application.*;
import javafx.application.*;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.*;


public class Main extends Application{

Stage window;
Scene scene1, scene2;


public static void main(String[] args) {
launch(args);

}

@Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;




//Create Elements for scene1
Label label = new Label("Welcome to scene 1 click button to go to scene 2");
Button button = new Button("Go to scene 2");
button.setOnAction(e -> window.setScene(scene2));


//Add Elements and set layout for scene1
StackPane layout1 = new StackPane();
layout1.getChildren().addAll(button, label);
scene1 = new Scene(layout1, 400, 400);



//Create Elements for scene2
Label label2 = new Label("This is scene 2 click button to go back to scene 1");
Button no2button = new Button("Go back to scene 1");
no2button.setOnAction(e -> window.setScene(scene1));

//Add Elements and set layout for scene2
StackPane layout2 = new StackPane();
layout1.getChildren().addAll(no2button, label2);
scene1 = new Scene(layout2, 400, 400);


window.setScene(scene1);
window.setTitle("CSS Alarm");
window.show();

}




}

Answer

Here :

   StackPane layout2 = new StackPane();
        layout1.getChildren().addAll(no2button, label2);
        scene1 = new Scene(layout2, 400, 400);

You aren't actually adding anything to layout2, but right below this you are setting layout 2 as the scene

scene1 = new Scene(layout2, 400, 400);


        window.setScene(scene1);
        window.setTitle("CSS Alarm");
        window.show();
Comments