The method in the Controller specified by the fmlx file in javafx must be public if the @ fxml annotation is not added.
The following is the test code:
Javafxapplication5/testjavafx/src/testfxml/testcontroller/samplecontroller. Java
Package testfxml. testcontroller;/** to change this template, choose tools | templates * and open the template in the editor. */import java.net. URL; import Java. util. resourcebundle; import javafx. event. actionevent; import javafx. fxml. fxml; import javafx. fxml. initializable; import javafx. scene. control. label;/***** @ author administrator */public class samplecontroller implements initializable {@ fxml PRI Vate label Label;/***. If @ fxml is added before the method name, the method can be private * if not written, only public */Public void handlebuttonaction (actionevent event) {// @ fxml/private void handlebuttonaction (actionevent event) {system. out. println ("You clicked me! "); Label. settext (" Hello world! ") ;}@ Override public void initialize (URL, resourcebundle Rb) {// todo }}
/Testjavafx/src/testfxml/testcontroller/javafxapplication5.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package testFXML.testController;import javafx.application.Application;import javafx.fxml.FXMLLoader;import javafx.scene.Parent;import javafx.scene.Scene;import javafx.stage.Stage;/** * * @author Administrator */public class JavaFXApplication5 extends Application { @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } /** * The main() method is ignored in correctly deployed JavaFX application. * main() serves only as fallback in case the application can not be * launched through deployment artifacts, e.g., in IDEs with limited FX * support. NetBeans ignores main(). * * @param args the command line arguments */ public static void main(String[] args) { launch(args); }}
/Testjavafx/src/testfxml/testcontroller/sample. fxml
<?xml version="1.0" encoding="UTF-8"?><?import java.lang.*?><?import java.util.*?><?import javafx.scene.*?><?import javafx.scene.control.*?><?import javafx.scene.layout.*?><AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="testFXML.testController.SampleController"> <children> <Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" /> <Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" /> </children></AnchorPane>
We can see the writing method in the controller.