如何在JavaFX中将当前场景更改为另一个场景?

时间:2014-04-12 15:19:19

标签: java netbeans javafx

有一个主舞台和一个控制器与他在第一阶段按钮,点击时,我想将当前场景改为下一个,怎么做?

1 个答案:

答案 0 :(得分: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类的实例传递给它。

请注意,这是我的代码的简短版本,为了简单起见,我不得不删除一些内容,因此如果您只是复制和粘贴,它可能会失败。如果我错过了什么让我知道。