我有一个 FXML 文件,其中包含带有 onMouseClicked 属性的按钮。我没有在 FXML 中设置 Controller ,因为我有构造函数注入(inject)的数据,我想提供给 Controller 。
<Button mnemonicParsing="false" onMouseClicked="#newWidgetRequestButtonClicked" text="New Widget..." />
我以编程方式设置 Controller ,我的 Controller 包含 FXML 中指定的方法。 Controller 函数执行,一切正常。
FXMLLoader loader = new FXMLLoader(getClass().getResource("MainView.fxml"));
MyController controller = new MyController(...);
loader.setController(controller);
我的问题在于 IntelliJ 对 .fxml 文件的检查。每次出现函数引用时,它都会报告“错误:(45, 54) 没有为顶级元素指定 Controller ”。我正在查看 IntelliJ 的检查规则,但在 JavaFX 部分没有看到这条规则。同样,程序构建和运行都很好,所以它不是真正的编译错误。我想禁用此错误通知。
我怎样才能避免这个错误?
最佳答案
您需要添加顶级元素 fx:controller。
假设您有一个基本的 fxml 文件,其中只有一个锚定 Pane 和一个按钮,如下面的 fxml。
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Button layoutX="102.0" layoutY="50.0" mnemonicParsing="false" text="Button" />
</children>
</AnchorPane>
在这种情况下,您的顶级元素将是锚定 Pane 。如果你想使用像 onMouseClicked
这样的 Action 按钮,你需要告诉 fxml 你的顶级元素(在本例中是 anchor Pane )中的 Controller 类,如下所示。
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.Controller">
<children>
<Button fx:id="buttonExample" layoutX="102.0" layoutY="50.0" mnemonicParsing="false" text="Button" />
</children>
</AnchorPane>
fx:controller="com.example.Controller"
行说我的控制类是 Controller 它在 com.example 包.
此外,您的元素 ID 应以 fx 开头,如示例中所示 (fx:id="buttonExample"
)。
关于java - 以编程方式设置 Controller 时为 "No Controller specified for top level element",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32868089/