-2

I built an application that works fine and had to do a ton of workarounds to get through the "not on FX thread" stuff, but overall I think I handled it nice. Anyways, I'm now looking to make this v2.0 app of the first one I did, much better with what I've learned so far.
One of the things that still baffle me is just STARTING the project, using netBeans when I start my FXML project I am presented with 3 documents:

FXMLDocument.fxml
FXMLDocumentController.java
(app name).java

Now, I understand the first two, they're linked together and basically the controller just makes all the GUI elements created in the FXML document work, however I can't seem to link the third file, the (appname).java file, it contains the start and main methods which are always called and it loads the FXML file from there, however my first app did not have a single line in this file (other than the ones it comes with already when starting a new project), I think this is probably not a good practice.
My question is, having these 3 files, how can I connect the FXMLController with the (appname).java file? for example if I press a button how can I make it do something thats coded in the (appname).java file instead of the FXMLController file? is this even possible?

  • It's not really clear what you're asking here, but I think some of it is already answered in http://stackoverflow.com/questions/33303167/javafx-can-application-class-be-the-controller-class – James_D Apr 28 '17 at 02:00

1 Answers1

1

The (app name).java file is your main class, this is the entry point for your application, this class will call the FXML and subsequently the FXML calls the Controller.

To access your FXMLController you will need to make sure that it is loaded first, you cannot access it before it is called to the stage (it will return with a nullExceptionError).

after it is loaded to stage however you can call it through:

private final FXMLLoader fxml = new FXMLLoader(getClass().getResource("fxmlnamehere.fxml"));

public void start(Stage mainStage) throws Exception {
    fxmlcontent = fxml.load();
    root = new Scene(fxmlcontent,width,height);
    mainStage.setScene(root);
    mainStage.show();

    FXMLDocumentController controller = fxml.<FXMLDocumentController>getController();
}

this will make controller what you would call to access information in your FXMLDocumentController class, just to note FXMLDocumentController will be replaced by the name of your controller class whatever you decide to call it.

to do a function in your (app name).java file from the controller class is much simpler, make sure that the function you wish to use is public then in the controller class use appName.functionName(); this will do the function functionName() that is withing appName (aka (app name).java).

TravisF
  • 459
  • 6
  • 13