舞台上有一个主舞台和一个控制器,当点击一个按钮时,我想将当前场景更改为下一个场景,如何操作?
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。这非常简单,您只需要从加载程序中获取控制器,并将应用程序类的实例传递给它
注意,这是我的代码的简短版本,为了简单起见,我不得不删除一些内容,所以如果你只复制&粘贴如果我错过了什么,请告诉我。