[英]How to change the current scene to another in JavaFX?
在第一個按鈕上有一個主舞台和一個控制器,當他單擊時,我想將當前場景更改為下一場景,該怎么做?
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類的實例傳遞給它即可。
請注意,這是我的代碼的簡短驗證,為簡單起見,我不得不刪除一些內容,因此,如果僅復制粘貼,則可能無法正常工作。 如果我錯過任何事情,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.