fxml 怎么切换场景
时间: 2023-10-10 10:11:38 浏览: 37
在 JavaFX 中使用 FXML 文件来创建场景时,可以使用 `FXMLLoader` 类来加载 FXML 文件,并通过 `Scene` 类来创建场景对象。要在应用程序中切换场景,可以使用 `Stage` 类的 `setScene()` 方法来设置当前显示的场景。
下面是一个示例代码,演示了如何在应用程序中切换场景:
1. 创建 FXML 文件
首先,需要创建一个 FXML 文件,用来定义场景的布局和控件。在这个示例中,我们创建了一个 `Main.fxml` 文件,其中包含了一个按钮和一个标签。
```xml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane fx:controller="sample.MainController" xmlns:fx="http://javafx.com/fxml">
<center>
<Button text="Switch Scene" onAction="#switchScene"/>
</center>
<bottom>
<Label text="This is Scene 1"/>
</bottom>
</BorderPane>
```
2. 创建控制器类
接下来,需要创建一个控制器类,用来处理 FXML 文件中的控件事件。在这个示例中,我们创建了一个 `MainController` 类,其中包含了一个 `switchScene()` 方法,用来切换场景。
```java
public class MainController {
public void switchScene(ActionEvent event) throws IOException {
// 加载 FXML 文件
FXMLLoader loader = new FXMLLoader(getClass().getResource("Second.fxml"));
Parent root = loader.load();
// 创建场景对象
Scene scene = new Scene(root, 400, 300);
// 获取主舞台对象
Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
// 切换场景
stage.setScene(scene);
}
}
```
在 `switchScene()` 方法中,我们首先使用 `FXMLLoader` 类的 `load()` 方法来加载 `Second.fxml` 文件,并创建一个 `Parent` 对象。然后,我们创建一个 `Scene` 对象,并将 `Parent` 对象作为参数传入。接下来,我们使用 `event.getSource()` 方法获取当前按钮对象,然后使用 `getScene()` 方法获取当前按钮所在的场景对象。最后,我们将新创建的 `Scene` 对象设置为主舞台的场景对象,从而实现场景切换。
3. 创建第二个 FXML 文件
最后,我们需要创建第二个 FXML 文件,用来定义第二个场景的布局和控件。在这个示例中,我们创建了一个 `Second.fxml` 文件,其中包含了一个标签和一个按钮。
```xml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane fx:controller="sample.SecondController" xmlns:fx="http://javafx.com/fxml">
<center>
<Button text="Switch Scene" onAction="#switchScene"/>
</center>
<bottom>
<Label text="This is Scene 2"/>
</bottom>
</BorderPane>
```
4. 创建第二个控制器类
最后,我们还需要创建一个控制器类,用来处理第二个 FXML 文件中的控件事件。在这个示例中,我们创建了一个 `SecondController` 类,其中包含了一个 `switchScene()` 方法,用来切换回第一个场景。
```java
public class SecondController {
public void switchScene(ActionEvent event) throws IOException {
// 加载 FXML 文件
FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml"));
Parent root = loader.load();
// 创建场景对象
Scene scene = new Scene(root, 400, 300);
// 获取主舞台对象
Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
// 切换场景
stage.setScene(scene);
}
}
```
在 `switchScene()` 方法中,我们首先使用 `FXMLLoader` 类的 `load()` 方法来加载 `Main.fxml` 文件,并创建一个 `Parent` 对象。然后,我们创建一个 `Scene` 对象,并将 `Parent` 对象作为参数传入。接下来,我们使用 `event.getSource()` 方法获取当前按钮对象,然后使用 `getScene()` 方法获取当前按钮所在的场景对象。最后,我们将新创建的 `Scene` 对象设置为主舞台的场景对象,从而实现场景切换。
注意:在实际开发中,可能需要使用更复杂的场景切换逻辑,例如使用场景栈来实现返回上一个场景的功能等。