gpt4 book ai didi

javafx - 我可以从 FXML 自动生成 Controller 类吗?

转载 作者:行者123 更新时间:2023-12-03 21:22:31 29 4
gpt4 key购买 nike

据我了解,当使用 FXML 描述 Java FX 场景时, Controller 类是手动编写的,然后可以从 .fxml 中引用它的成员变量和方法。文件。使用 FXMLLoader 加载场景时,成员变量设置为相应的场景元素,方法自动连接到相应的事件。这可行,但非常麻烦,因为需要在两个地方进行更改,并且任何错误只会在运行时出现。

我见过其他 GUI 框架,它们允许您从场景描述生成 Controller 作为需要实现以访问场景元素和处理事件的抽象类。我的意思的一个例子:

我将创建以下 .fxml文件(例如,使用 JavaFX 场景生成器):

<AnchorPane ... >
<children>
<Button fx:id="button" ... text="Button" onAction="#buttonPressed" />
</children>
</AnchorPane>

在我的构建过程中,以下 .java将创建文件(例如,使用 Maven 插件):
abstract class TestController {
protected final Parent root;
protected final Button button;

{
// Load test.fxml file
// Assign scene elements to root and button
// Attach event handler to the button that calls buttonClicked()
}

protected abstract void buttonClicked(ActionEvent event);
}

然后,我可以多次创建该 Controller 的具体实现:
final class TestControllerImpl extends TestController {
TestControllerImpl(String buttonLabel) {
button.setText(buttonLabel);
}

@Override
protected void buttonClicked(ActionEvent event) {
button.setText("I've been clicked! What a great day!");
}
}

是否有一个目标是这样做的项目?或者这种方法应用于 FXML 是否存在问题?

我看到这种方法有以下好处:
  • Controller 的成员变量和方法的声明是自动生成的。
  • 所有成员变量都是最终的和 protected ,而不是非最终的,要么是公共(public)的,要么是带注释的。
  • 方法也是如此,它们是 protected ,而不是公共(public)的或注释的。
  • 不实现方法或拼写错误的名称将导致编译器错误。
  • 场景的编程设置可以在构造函数中完成,而不是 initialize()方法,因为构造函数将在场景加载并将其元素分配给成员变量后运行。
  • 最佳答案

    现在 SceneBuilder、NetBeans 和 Eclipse 都支持这一点。请注意,这在 NetBeans 和 SceneBuilder 中是开箱即用的,但在 Eclipse 中,您首先需要 e(fx)clipse 插件。

    场景生成器:
    在编辑器中打开 FXML 文件后,进入菜单选择“查看”和“显示示例 Controller 骨架”。

    eclipse :
    打开 fxml 文件,使内容显示在代码编辑 Pane 中(您应该将 fxml 视为纯文本 xml,在 Eclipse 中具有语法高亮显示,而不是在 SceneBuilder 中以可视方式呈现)。右键单击 Eclipse 中的代码并选择“代码”,然后选择“生成 Controller ”。

    网 bean :
    在 NetBeans 中更简单,在项目资源管理器中右键单击 fxml 文件并选择“制作 Controller ”。

    关于javafx - 我可以从 FXML 自动生成 Controller 类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21575158/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com