You need to hook your FXML file up to a controller.
In the root node of the FXML page, type the following:
fx:controller="package.subpackage.ControllerName"
Where the string is the relative package path of the Controller. Notice that it doesn't matter if the controller is in a different package than the FXML file, you always declare a path from the source package. You can also let Netbeans do this for you, by right-clicking the FXML file and selecting 'Make Controller'.
If you have given any elements an fx:id
, JavaFX will inject them into your controller if you declare them with an @FXML
tag like this:
@FXML private Button btnNew;
You can declare events in the same way. For example:
@FXML
void btnNew_OnAction(ActionEvent event) {
//body
}
UPDATE:
I think you should reconsider your design. An FXML file can only be tied to one controller. If you have a menubar, the behaviour of the buttons on that menubar are probably related and I think it's a bad idea to seperate that behaviour into different controller classes. The way I would solve it is to have a single controller that handles all the events for all the buttons in the menubar.
How have you set up your controllers? FXML is a form of MVC(Model-View-Controller). The way I usually do it is to have all the data away from the controllers, in the Model layer. I then have the controllers interact with the data and listen for changes. That way, you don't need to have the event handlers spread out in specific controllers, because they all have access to the model layer. I found this answer that explains this quite well. It injects a Context
object into the controllers. A good solution for small-scale applications, but beware of creating a God-object this way though. :)
That said, if you really really want to have multiple controllers for various GUI elements on the same screen, that's totally possible. You need to have a different FXML file for each controller, though. Take a look at this answer, it addresses the issue quite well: creating multiple controllers.