I am trying to create a button in JavaFX using Scene Builder but I am having some issues. Here is my code :
MainDesign.java
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MainDesign extends Application {
@Override
public void start(Stage primaryStage) {
try {
BorderPane root = (BorderPane) FXMLLoader.load(getClass().getResource("application/Design.fxml"));
Scene scene = new Scene(root, 400, 400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
DesignController.java:-
package application;
import java.awt.Button;
import javafx.fxml.FXML;
public class DesignController {
@FXML private Button b1;
}
Design.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.DesignController">
<center>
<Button fx:id="b1" mnemonicParsing="false" text="Button" BorderPane.alignment="CENTER" />
</center>
</BorderPane>
Error:
Exception in Application start method
java.lang.reflect.InvocationTargetException
Caused by: java.lang.RuntimeException: Exception in Application start method
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x22e6b9c) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x22e6b9c
Exception running application application.MainDesign
Thus , it's generating an exception in MainDesign.java
file , I guess its regarding FXML loader.
Please help me if anyone has a solution for such issue!!!
There is a confusion with the
Button
component; in Design.fxml you're usingjavafx.scene.control.Button
and in DesignController.java you're usingjava.awt.Button
. JavaFX and Java AWT are independant libraries, so it raises a problem when FXML loader is reading this line:because it cannot make a connection between
b1
in your FXML file andb1
in your controller. You have to importjavafx.scene.control.Button
in your controller.