JavaFX:LoadException 解析按钮事件处理程序的 onAction

JavaFX: LoadException resolving onAction for event handler of a button

我是 JavaFX 的新手。尝试按照教程生成场景并将事件处理程序与按钮相关联。

我创建了一个 Main.FXML 并在 SceneBuilder 中进行了编辑。由于我在 IDE 中添加了 SceneBuilder 的路径,它能够检测到我的主控制器。我写了一个函数来生成随机数。

public class MainController {

    public static void generateRandom(ActionEvent event) {
        Random rand = new Random();
        int myrand = rand.nextInt(500) + 1;
        System.out.print(Integer.toString(myrand));
    }
}

在 scenebuilder 中,它在控制器中检测到此方法,可以轻松地将其添加为按钮的 OnAction 的事件处理程序。 Main.FXML 操作后更新。

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>


<AnchorPane prefHeight="300" prefWidth="500" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.111" fx:controller="application.MainController">
   <children>
      <Button layoutX="204.0" layoutY="204.0" mnemonicParsing="false" onAction="#generateRandom" text="Button" />
      <Label layoutX="138.0" layoutY="36.0" prefHeight="144.0" prefWidth="210.0" />
   </children>
</AnchorPane>

我的主要应用class如下:

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) throws IOException {
        Parent root = FXMLLoader.load(getClass().getResource("/application/Main.fxml"));
        Scene scene = new Scene(root,400,400);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        primaryStage.setTitle("My Title");
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
}

当我 运行 应用程序时,出现错误:

javafx.fxml.LoadException: Error resolving onAction='#generateRandom', either the event handler is not in the Namespace or there is an error in the script. /C:/Users/Oscar/Workspace/Sunoco/bin/application/Main.fxml:10

表明它可能与 ActionEvent 的错误导入有关,但事实并非如此。此外,一切都是使用 SceneBuilder 和 Eclipse 自动设置的。那么为什么我会收到此错误?

我认为如果在 eventMethod 上使用 @FXML 注释,问题就会得到解决。此外,尽量不要在控制器中将方法设为静态,因为它可能是confusing/misleading。如果您需要从其他地方访问该方法,请考虑在单独的(类似实用程序)class.

中声明它