JavaFX,在同一个阶段的不同场景中拥有相同的对象/项目?

时间:2018-04-17 09:28:07

标签: java user-interface javafx scene stage

我正在使用JavaFX中的应用程序,我需要在其间切换多个场景。但似乎我不能拥有相同的项目(示例:工具栏)在多个场景中,它只显示其中一个场景中的项目。也许不可能在不同的场景中拥有相同的项目,所以我的问题是我该怎么做呢?我是否需要多个阶段?如果是这种情况,我如何在阶段之间进行更改?我没有在这个项目中使用FXML,我们必须对它进行编码..我目前的代码:

public class Main extends Application {

    private Label time;

    private int minute;
    private int hour;
    private int second;


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

    // CLOCK RUNNING

    public void initialize() {

            Timeline clock = new Timeline(new KeyFrame(Duration.ZERO, e -> {
                Calendar cal = Calendar.getInstance();
                second = cal.get(Calendar.SECOND);
                minute = cal.get(Calendar.MINUTE);
                hour = cal.get(Calendar.HOUR);
                //System.out.println(hour + ":" + (minute) + ":" + second);
                time.setText(hour + ":" + (minute) + ":" + second);
            }),
                    new KeyFrame(Duration.seconds(1))
            );
            clock.setCycleCount(Animation.INDEFINITE);
            clock.play();
        }


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

        //Specify The Size of Scenes, and the scenes.
        BorderPane root1 = new BorderPane();
        BorderPane root2 = new BorderPane();
        Scene scene1 = new Scene(root1, 1100, 900);
        Scene scene2 = new Scene(root2,1100,900);


        // Get CSS File
        scene1.getStylesheets().add("Helmuth.css");


        time = new Label("Time:");
        initialize();


        //ToolBar i want this to be shown in both scenes //

        Button homebt = new Button("Home");
        Button tabelbt = new Button("Tabel");


        ToolBar toolBar = new ToolBar();
        toolBar.getItems().add(homebt);
        toolBar.getItems().add(tabelbt);
        toolBar.getItems().add(time);


        Label label1 = new Label("Welcome to the first scene!");
        Button button1 = new Button("Go to scene 2");
        button1.setOnAction(e -> primaryStage.setScene(scene2));

        VBox layout1 = new VBox();
        layout1.getChildren().addAll(button1,toolBar);

        Button button2 = new Button("Go Back");
        button2.setOnAction(e -> primaryStage.setScene(scene1));

        VBox mainbox = new VBox();
        mainbox.setAlignment(Pos.TOP_CENTER);
        mainbox.getChildren().addAll(button2, toolBar);


        // Start scene 1
        root2.setCenter(mainbox);
        root1.setCenter(layout1);
        primaryStage.setScene(scene1);
        primaryStage.setTitle("Helmuth");
        boolean b = false;
        primaryStage.setResizable(b);
        primaryStage.show();
    }
}                                                                                           

1 个答案:

答案 0 :(得分:0)

为什么要在不同的场景之间切换。解决问题的方法可能就是交换场景的根节点。

相关问题