首页 > 解决方案 > 在场景中不显示任何按钮

问题描述

它是一个简单的 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();
 }
}

标签: javafx

解决方案


您有一些语法错误,但是这可以工作,您之前设置了相同的场景,所以它会按照它被告知的方式切换到相同的场景,并且您只需将按钮 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();
    }
}

推荐阅读