在场景内不显示任何按钮

时间:2018-09-19 14:29:31

标签: javafx

  

它的一个简单的javafx程序将在两个场景之间切换。   程序可以正常编译,但不显示场景中的任何组件。   我使用了两个布局,两个按钮和两个场景。   假设所有必需的软件包都已导入。   源代码:github.com/tmtanzeel/javafx/Program5.java

public class Program5 extends Application {
  Button button1;
  Button button2;

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

  @Override
  public void start(Stage primaryStage) throws Exception {
  button1=new Button();
  button2=new Button(); 

  button1.setText("Yes");
  button2.setText("No");

  StackPane layout1=new StackPane();
  layout1.getChildren().add(button1);

  StackPane layout2=new StackPane();
  layout2.getChildren().add(button1);

  Scene scene1=new Scene(layout1, 450,250);
  Scene scene2=new Scene(layout2, 250, 450);

  button1.setOnAction(e -> {
    primaryStage.setScene(scene1);
  });

  button2.setOnAction(e -> {
    primaryStage.setScene(scene2);
  });

  primaryStage.setScene(scene1);
  primaryStage.setTitle("Window-1");
  primaryStage.show();
 }
}

1 个答案:

答案 0 :(得分:3)

您有一些语法错误,但此方法可以使您先前设置了相同的场景,因此它被告知要切换到同一场景,并且您只在两个屏幕上添加了按钮1

public class Main extends Application {

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

    @Override
    public void start(Stage primaryStage) {
        Button button1 = new Button();
        Button button2 = new Button();

        button1.setText("Yes");
        button2.setText("No");

        StackPane layout1 = new StackPane();
        layout1.getChildren().add(button1);

        StackPane layout2 = new StackPane();
        layout2.getChildren().add(button2); //This should be button2

        Scene scene1 = new Scene(layout1, 450, 250);
        Scene scene2 = new Scene(layout2, 250, 450);

        button1.setOnAction(e -> primaryStage.setScene(scene2)); //You set the wrong scene here

        button2.setOnAction(e -> primaryStage.setScene(scene1)); //And here

        primaryStage.setScene(scene1);
        primaryStage.setTitle("Window-1");
        primaryStage.show();
    }
}