1

In the Controller(or maybe the Main or another file, I'm not sure how all this works), we have the following:

String foo = "Foo.";

And in Scene Bilder-generated FXML, something like this:

<Button mnemonicParsing="false" prefHeight="25.0" prefWidth="61.0" text="Browse" />

How do I make the value of foo appear as the text on the button? And where should I store it, the controller or somewhere else? I'm still perplexed about how do the Main file, the controller(s), and FXML files exactly come together.

Sargon1
  • 854
  • 5
  • 17
  • 48

2 Answers2

5

You need to define an ID for the button (within the scene builder or just per hand, by adding the fx:id="yourId" tag).

Within your controller class, you then have to add

@FXML
private Button yourId;

You now can access the Button to call the corresponding methods you need, in your example yourId.setText(foo);

If you want to access the instance of your ControllerClass from e.g. your Application class, you can do the following:

FXMLLoader loader = new FXMLLoader(your_fxml_resource);
Parent parent = loader.load();
YourControllerClass controller = loader.getController();//add this line to get your controller instance.
M. Reyes
  • 140
  • 11
2

You give the controller access to the UI elements defined in the FXML by injection. Specifically, in the FXML, give the UI element a fx:id attribute:

<Button fx:id="someButton" mnemonicParsing="false" prefHeight="25.0" prefWidth="61.0" text="Browse" />

Now in your controller, define an @FXML-annotated field with a name that matches the fx:id attribute value:

public class Controller {

    @FXML
    private Button someButton ;

}

Now you can configure the button with whatever logic you need:

public class Controller {

    @FXML
    private Button someButton ;

    public void initialize() {
        String foo = "foo" ;
        someButton.setText(foo);
    }
}

To answer the "how does all this fit together" part of your question, consider the FXML and controller as a pair. The FXML defines the layout, while the controller defines the logic (handling user input, etc). The controller has access to the elements of the UI defined in the FXML file using the mechanism described above.

When an FXMLLoader loads the FXML file, in the default setup, the FXMLLoader creates an instance of your controller class, injects the @FXML-annotated fields into the controller instance, and calls the controller instance's initialize() method.

The Application subclass exists just as the starting point for your application. It will typically just load an FXML file, put the root of the FXML in a Scene and display the Scene in a primary stage. If you have a more complex application, you might also start up some services and background threads here.

James_D
  • 201,275
  • 16
  • 291
  • 322