Issue
(I am using Scene Builder...)
Here is the MusicGeneratorGUI
class...
public class MusicGeneratorGUI extends Application {
@FXML private Sphere icon;
...
}
Here I have instantiated the object from the FXML file with the same ID...
<Sphere fx:id="icon" ... />
However, System.out.println(icon);
in the main method of the controller class produces null.
The 'icon' Sphere object is null.
Here is the main class... ('controller class')
public class Main implements Initializable {
@FXML public static Sphere icon;
public static void main(String args[]) {
System.out.println(icon);
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
//Nothing here...
}
...
}
Solution
You need to create an instance of your loader.
FXMLLoader loader = new FXMLLoader(getClass().getResource("main.fxml"));
Then you can get access to an instance of your controller.
Main main = loader.getController();
Then you can access the icon
from the controller.
System.out.println(main.icon);
Note, you can still get the parent via.
Parent root = loader.load();
You might want to consider doing this from the initialize method of the controller, then you don't need to expose the icon of the Controller. Also, why is your icon static? I think you need to ditch the static.
Answered By - matt
Answer Checked By - David Marino (JavaFixing Volunteer)