在javafx上切换场景

时间:2017-11-28 12:00:54

标签: java javafx

我有这个代码,我想当我点击btn1时,必须将sceneStage的场景从scene1切换到scene2, 我是跟随tuto,它适用于视频,但不适合我 这里的代码(不是setOnAction中的system.ou.println工作)

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;

public class SwitchingScenes4 extends Application{

    Stage window;
    Scene scene1 ,scene2;

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

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

    Label label = new Label("Welcome to scene 1");
    Button btn = new Button("Go to Scene2");
    btn.setOnAction(e ->{
        window.setScene(scene2);
        System.out.println("ee");
    });

    VBox layout1 = new VBox(20);
    layout1.getChildren().addAll(label, btn);
    scene1 = new Scene(layout1, 200, 200);

    //btn2
    Button btn2 = new Button("Go to Scene1");
    btn.setOnAction(e -> {
        //primaryStage.setScene(scene1);
        System.out.println("ff");       
    });

    StackPane layout2 = new StackPane();
    layout2.getChildren().add(btn2);
    scene2 = new Scene(layout2, 200, 200);

    //Launching
    window.setTitle("Scenes");
    window.setScene(scene1);
    window.show();          
    }
}

1 个答案:

答案 0 :(得分:0)

您混淆了将过渡事件处理附加到场景1的按钮

//btn2
Button btn2 = new Button("Go to Scene1");
btn2.setOnAction(e -> {
    primaryStage.setScene(scene1);
    System.out.println("ff");
});