2014-04-12 118 views

回答

0

Main.java:

@Override 
public void start(Stage primaryStage) throws Exception{ 
    FXMLLoader loader = new FXMLLoader(); 
    Parent root = (Parent) loader.load(getClass().getResource("first.fxml").openStream()); 
    FirstController firstController = loader.getController(); 
    firstController.setStage(primaryStage); 

    primaryStage.setTitle("Stage"); 
    primaryStage.setScene(new Scene(root)); 
    primaryStage.show(); 
} 


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

first.fxml:

<?import javafx.scene.control.Button?> 
<?import javafx.scene.control.Label?> 
<?import javafx.scene.layout.*?> 
<GridPane fx:controller="sample.FirstController" 
     xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10"> 
    <Label text="first scene" GridPane.columnIndex="0" GridPane.rowIndex="0"/> 
    <Button text="second" onAction="#second" GridPane.columnIndex="0" GridPane.rowIndex="1" /> 
</GridPane> 

FirstController.java:

private Stage mStage; 

public void setStage(Stage mStage) { 
    this.mStage = mStage; 
} 


public void second(ActionEvent actionEvent) throws IOException { 
    FXMLLoader loader = new FXMLLoader(); 
    Parent root = (Parent)  loader.load(getClass().getResource("second.fxml").openStream()); 
    SecondController secondController = loader.getController(); 
    secondController.setStage(mStage); 

    mStage.setTitle("second scene"); 
    mStage.setScene(new Scene(root)); 
    mStage.show(); 
} 

second.fxml

<?import javafx.scene.control.Button?> 
<?import javafx.scene.control.Label?> 
<?import javafx.scene.layout.*?> 
<GridPane fx:controller="sample.SecondController" 
     xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10"> 
    <Label text="second scene" GridPane.columnIndex="0" GridPane.rowIndex="0"/> 
    <Button text="first" onAction="#first" GridPane.columnIndex="0" GridPane.rowIndex="1" /> 
</GridPane> 

SecondController.java

private Stage mStage; 

public void setStage(Stage mStage) { 
    this.mStage = mStage; 
} 


public void first(ActionEvent actionEvent) throws IOException { 
    FXMLLoader loader = new FXMLLoader(); 
    Parent root = (Parent) loader.load(getClass().getResource("first.fxml").openStream()); 
    FirstController firstController = loader.getController(); 
    firstController.setStage(mStage); 

    mStage.setTitle("first scene"); 
    mStage.setScene(new Scene(root)); 
    mStage.show(); 
} 

而且second.fxml可以是你喜歡的任何FXML。它非常簡單,你只需要從加載器獲取控制器並將Application類的實例傳遞給它。

請注意,這是我的代碼的簡短版本,我不得不刪除一些簡單的東西,所以它可能不會工作,如果你只是複製&粘貼。如果我錯過了任何事情,請告訴我。

+0

謝謝!但是我會犯錯誤,setStage不會被調用。爲什麼? –

+0

我添加成員公共FirstController控制器;在主類中,並且調用controller = loader.getController(); controller.setStage(stage); // <<這是重要部分 –

+0

好的,我編輯了代碼。現在應該是工作示例(從IDE複製並粘貼)。我認爲這不是最好的方法,但它取決於你的應用程序架構。這只是它如何工作的基本概念。如果您滿意,請接受它作爲答案並投票:) – Srneczek