Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFx FXML load file issues with setting root

New to javaFx and wanting to use scenebuilder for GUI development, i've come across an issue with no luck searching the website nor the web in general for my problem, although similar questions have been asked, thought a different perspective could be needed. I am trying to load an FXML file through Netbeans after a quick build to test functionality so the code is simple, but i cannot get the root file to be set in the controller. my code is the following public class Divergex extends Application {

@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("DivergexGUI.fxml"));


    Scene scene = new Scene(root);
    scene.setRoot(root);

    stage.setScene(scene);
    stage.show();
}

Ive tried suggestions in changing fxroot to a Vbox with no luck, i continue to get a Load exception on the compile :

Exception in Application start method... Caused by: javafx.fxml.LoadException: Root hasn't been set. Use method setRoot() before load.

yet when i use

scene.setRoot(root); 

the same exception is experienced

i've narrowed the issue down to the fact that my FXML file is unable to be set as a root in the Parent object but have had no luck in tackling this. Any suggestions would be great thanks.

like image 336
Nrandazzo Avatar asked May 19 '14 03:05

Nrandazzo


People also ask

What method is used to load an FXML file into the root node of the app?

Loading an FXML File The root GUI component (the VBox object) is obtained via the load() method.


1 Answers

<fx:root> specifies a "dynamic root" for your FXML file; this means the root of the FXML file is an object that is set on the loader prior to loading the file. This is typically used for custom controls, where you want the control to be a subclass of Node that can be instantiated using regular Java code, but want to define its layout using FXML. Proper use of <fx:root> (or at least an example of how it can be used) is shown in the standard documentation. In particular, if you use <fx:root> you must:

  1. Create an FXMLLoader instance, instead of using the static convenience FXMLLoader.load(URL) method
  2. Call setRoot(...) on that instance, and pass in the object that is to be the root of the FXML.

For standard FXML use, you just use a regular instance declaration as the root. Almost every example available works this way: probably the best place to start is the official tutorial. In your case, since you want a VBox, you probably just need

<VBox xmlns="javafx.com/javafx/8"; xmlns:fx="javafx.com/fxml/1"; fx:controller="divergex.DivergexGUIController">
<!-- ... -->
</VBox>

Edit If Netbeans is giving you issues, I recommend using Eclipse with the e(fx)clipse plugin. There's a very barebones, but pretty much all you need, tutorial.

like image 188
James_D Avatar answered Oct 05 '22 22:10

James_D