我是JavaFX的新手。尝试按照教程生成一个场景并将按钮与事件处理程序关联。JavaFX:LoadException为按钮的事件处理程序解析onAction
我创建了一个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>
我的主应用程序类是如下:
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
Error resolving “onAction” while loading FXML表明,它可能有错误的进口换做ActionEvent
不是这种情况。再加上一切都是使用SceneBuilder和Eclipse自动设置的。那么,为什么我会得到这个错误?
看起来像“静态”是造成问题。在我拿出来之后,它没有使用@ FXML注解。 – ddd