我有一个FXML文件,其中包含带有onMouseClicked属性的按钮。我没有在FXML中设置一个控制器,因为我有构造函数注入我想要提供给Controller的数据。
<Button mnemonicParsing="false" onMouseClicked="#newWidgetRequestButtonClicked" text="New Widget..." />
我以编程方式设置Controller,我的控制器包含FXML中指定的方法。 Controller函数执行,一切正常。
FXMLLoader loader = new FXMLLoader(getClass().getResource("MainView.fxml"));
MyController controller = new MyController(...);
loader.setController(controller);
我的问题在于IntelliJ对.fxml文件的检查。每次出现函数引用时,它都会报告&#34;错误:(45,54)没有为顶级元素&#34;指定控制器。我正在查看IntelliJ的检查规则,并且在JavaFX部分中没有看到此规则。同样,程序构建并运行得很好,因此它不是真正的编译错误。我想禁用此错误通知。
如何避免此错误?
答案 0 :(得分:3)
即便如此,我也不喜欢这些通知。我以编程方式设置控制器。要禁用它,您需要将突出显示级别设置为none。 要执行此操作,请打开fxml文件,在右侧的最底部,您将看到一个hector图标。单击hector图标并通过拖动滑块将高亮级别设置为none。
您需要重新启动IDE才能使更改生效。仅对该文件的突出显示将设置为none。在我们再次将突出显示级别设置为none之前,其他文件的突出显示行为不会发生任何变化。
如果您无法找到hector图标,请使用以下链接。 https://www.jetbrains.com/help/idea/status-bar.html
答案 1 :(得分:1)
您需要添加顶级元素fx:controller。
假设您有一个基本的fxml文件,其中只有一个锚点窗格,其中包含一个像下面的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>
在这种情况下,您的顶级元素将是锚点窗格。如果你想使用像onMouseClicked
这样的动作按钮,你需要告诉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" 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"
行说我的控件类是控制器,它位于 com.example包中。
此外,您的元素ID应以 fx 开头,例如示例(fx:id="buttonExample"
)。