Question

This is a class project where we needed to set up our GUI on an fxml doc. I have gotten the layout set on the fxml however I wasn't sure how I could get the buttons to print out statement or call methods that were in different java classes. I tried searching online but didn't really understand it. Could someone tell me how I can go about having the GUI be more than just a button and have it perform things like mathamatical methods?

Thank You

Était-ce utile?

La solution

Here is an example FXML:

https://github.com/SnakeDoc/superD/blob/master/src/com/vanomaly/superd/view/MainWindow.fxml

Here is an example controller class:

https://github.com/SnakeDoc/superD/blob/master/src/com/vanomaly/superd/controller/MainWindowController.java

As you will notice, in your FXML you can specify a Controller. Or, like in this example:

https://github.com/SnakeDoc/superD/blob/master/src/com/vanomaly/superd/Main.java

You can specify your controller in java code during the start up of your JavaFX application.

It doesn't matter which, but don't do both (you will get an error).

Then, in your controller, you can use the @FXML annotation to link that variable to the correct GUI control in your FXML that has the same fx:id as the variable name (see examples again).

Then you can just use that variable like any other GUI control. :)

Example:

@FXML private Label targetLabel;

Is defined in the controller.

And in the FXML, there is:

<Label fx:id="targetLabel" layoutX="26.0" layoutY="16.0" styleClass="contrast-label" text="Target(s) :" />

Notice how the fx:id is the same as the variable name? This tells JavaFX to link them (they are the same).

Autres conseils

If you want your fxml buttons to use methods of other classes, you will need to do this through the controller declared with the fx:controller. In your controller, make the method and import whatever classes you need into your controller class. The button in the fxml will know the controller class but will need to know the method to call when clicked. Supply the method using onAction in the fxml portion where the is.

I'd recommend checking out "Add Button and Text" section of the oracle javafx tutorial here

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top