I am new to JavaFX. Trying to follow a tutorial to generate a scene and associate eventhandler with a button.
I created a Main.FXML and edited in SceneBuilder. Since I added SceneBuilder's path in my IDE, it is able to detect my main controller. I wrote a function to generate random number.
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));
}
}
In scenebuilder, it detects this method in controller which can be easily added as eventhandler for OnAction of the button. Main.FXML is updated after the operations.
<?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>
My main application class is as below:
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);
}
}
When I run the app, I got error:
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 suggests it may have to do with wrong import for ActionEvent
which is not the case. Plus everything is set up automatically using SceneBuilder and Eclipse. So why am I getting this error?