我是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