javafx中的控制器和fxml

来源:互联网 发布:2015年双11淘宝交易额 编辑:程序博客网 时间:2024/05/29 07:12

在javafx中fmlx文件指定的控制器中的方法如果没有加上@FXML注解的话,就必须是public

以下是测试代码:

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    private Label label;    /**     * 两种写法,如果在方法名的前面放就加上@FXML则方法可以是private     * 如果不写,就只能是公开的     */    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 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>

可以看到在控制器中的写法