FXML中定义不了handleCloseButton
时间: 2024-03-15 20:43:55 浏览: 17
如果在 FXML 文件中定义了一个按钮,你可以使用 `onAction` 属性指定按钮被点击时要执行的处理方法。但是,在 FXML 文件中不能直接定义处理方法,你需要在控制器类中实现这些方法。
首先,你需要在 FXML 文件中为按钮指定一个 `fx:id` 属性,以便在控制器类中引用该按钮。例如:
```xml
<Button fx:id="closeButton" text="Close" onAction="#handleCloseButton"/>
```
然后,在控制器类中,你需要定义一个名为 `handleCloseButton` 的方法来处理按钮点击事件。例如:
```java
public class MyController {
@FXML
private Button closeButton;
@FXML
private void handleCloseButton(ActionEvent event) {
Stage stage = (Stage) closeButton.getScene().getWindow();
stage.close();
Platform.exit();
System.exit(0);
}
}
```
这里的 `handleCloseButton` 方法使用 `@FXML` 注解标记,以便在 FXML 文件中引用。它需要一个 `ActionEvent` 参数,因为它是一个事件处理方法。在方法中,我们使用 `closeButton` 的 `getScene()` 方法获取 `Scene` 对象,然后使用 `getWindow()` 方法获取当前窗口的 `Stage` 对象。接下来,我们使用 `stage.close()` 方法关闭窗口,并调用 `Platform.exit()` 和 `System.exit(0)` 方法停止程序的运行。