I already searched the deepest depths of the interweb but no answer will seem to be found -.-
The problem is in my javaFx programm i want to write. But i can\'t mak
The fx:controller
attribute is expecting the fully qualified classname of the controller class. I.e. assuming you have
package main.java.controllers ;
public class MainUIController { ... }
you should have
fx:controller="main.java.controllers.MainUIController"
I suggest to change the project structure. The resources should not be resided in the sources itself. So my suggestion is the following project structure:
src
|-main
|-java <-- This should be your 'sources root'
|-application <-- The application itself is within the new sources root
|-controllers
|here are my controllers
|-dao
|-service
|-resources <-- all resources (css files, images, fxml files) should be with a subfolder of the resources. This folder should be marked as 'resources root'
|-css
|-images
|-view
|here are the fxml files
This structure can be set up in any IDE. How you can set it up depends on the IDE itself. Normally you can simply right-click the folder in the overview and mark is as sources/resources root. The exact names for 'source root' and 'resources root' depend on the IDE.
The Main
is now in the package application
and the MainUIController
is in the package controllers
.
In the FXML-File you should specify:
fx:controller="controllers.MainUIController"
Loading the FXML-File should work with:
AnchorPane root = (AnchorPane) FXMLLoader.load(getClass().getClassLoader().getResource("view/MainUI.fxml"));
As a reference for the following explanation, have a look here:
The ClassLoader
always starts at the root of your resources. If you only use getClass
, the path to the resource is a relative path. After dealing with it several times, I for myself have decided to always use absolute paths and therefore use the getClassLoader
.
As explained in the link above, please note that
getClass().getClassLoader().getResource("view/MainUI.fxml");
could be replaced by
getClass().getResource("view/MainUI.fxml");
I think that I somewhere read, that it is better to directly use the InputStream
if available, as dealing with URLs within JAR-Files can be tricky sometimes (but I currently can't find a reference to support that). So as an alternative to the getResource(..)
, you could use:
FXMLLoader loader = new FXMLLoader();
Parent root = loader.load(getClass().getClassLoader().getResourceAsStream("view/MainUI.fxml");