2016-05-13 143 views
0

我在class1中創建了一個場景,然後我在class2中創建了一個scene2。 如何在它們之間切換?在場景之間切換JavaFX

public class class1 extends Application{ 

Stage window1; 
BorderPane layout1; 
Scene scene1; 

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

@Override 
public void start(Stage primaryStage) throws Exception { 
    window1 = primaryStage; 
    window.setTitle("Stage 1"); 

    // And here is a button which switchs between scenes or stages, 
    //i dont know what is better.So: 

button.setOnAction(e -> ?????????) 



    scene1 = new Scene(layout1, 800,600); 
    window1.show(); 
} 
} 

這是第二堂課,我有另一個場景。

public class class2 extends Application{ 

Stage window2; 
BorderPane layout2; 
Scene scene2; 

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

@Override 
public void start(Stage primaryStage) throws Exception { 
    window2 = primaryStage; 
    window2.setTitle("Stage 2"); 

    scene2 = new Scene(layout, 800,600); 
    window2.show(); 
} 
} 
+4

您選擇的方法將不起作用,因爲每個運行時只能有一個'Application'。其餘的請看http://stackoverflow.com/questions/37200845/how-to-switch-scenes-in-javafx – hotzst

回答

0

我寫了這個控制器來跟蹤不同的scenegraphes和切換我的舞臺的內容沒有麻煩。

也許你想看看FXML: http://docs.oracle.com/javafx/2/fxml_get_started/why_use_fxml.htm#CHDCHIBE

public class ScreenController { 
    private HashMap<String, Pane> screenMap = new HashMap<>(); 
    private Scene main; 

    public ScreenController(Scene main) { 
     this.main = main; 
    } 

    protected void addScreen(String name, Pane pane){ 
     screenMap.put(name, pane); 
    } 

    protected void removeScreen(String name){ 
     screenMap.remove(name); 
    } 

    protected void activate(String name){ 
     main.setRoot(screenMap.get(name)); 
    } 
} 

因此我可以這樣寫:

ScreenController screenController = new ScreenController(scene); 
screenController.add("layout1", layout1); 
screenController.add("layout2", layout2); 
screenController.add("testSwitch", FXMLLoader.load(getClass().getResource("TestSwitch.fxml"))); 

button.setOnAction(e -> screenController.activate("layout2")); 

這是一個全屏應用解決方法,其中MacOS的全屏過渡是每次舞臺切換場景時都會顯示。