Exception in Application start method [Java FX]

1k Views Asked by At

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

Error Image

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!!!

1

There are 1 best solutions below

0
On

There is a confusion with the Button component; in Design.fxml you're using javafx.scene.control.Button and in DesignController.java you're using java.awt.Button. JavaFX and Java AWT are independant libraries, so it raises a problem when FXML loader is reading this line:

@FXML private Button b1;

because it cannot make a connection between b1 in your FXML file and b1 in your controller. You have to import javafx.scene.control.Button in your controller.