点击按钮后label文本会发生变化:
设置label的ID:fx:id
:
自动生成属性:
<build> <finalName>HelloJavaFX</finalName> <resources> <resource> <!-- 这里是放在 src/main/java--> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.fxml</include> <include>**/fxml/*.fxml</include> <!-- 如果想要弄个包名专门放fxml文件,像上一行这样添加设置 --> <!-- 之后,使用getResource("fxml/xx.fxml")这样子 --> </includes> <filtering>false</filtering> </resource> </resources> </build>
<?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.control.*?> <?import javafx.scene.layout.*?> <AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="cn.zxl.Controller.Controller"> <children> <Button layoutX="273.0" layoutY="189.0" mnemonicParsing="false" onAction="#test" text="我是按钮" /> <Label fx:id="label2" layoutX="273.0" layoutY="151.0" text="Label" /> </children> </AnchorPane>
package cn.zxl.Controller; import javafx.scene.control.Label; /** * @Description: //TODO 控制器类 * @Author: zhangxueliang * @Create: 2021-05-27 11:35 * @Version: 1.0 **/ public class Controller { public Label label2; public void test(){ System.out.println("点击了按钮"); label2.setText("你点击了按钮"); } }
package cn.zxl.Controller; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; /** * @Description: //TODO 建立FXML * @Author: zhangxueliang * @Create: 2021-05-27 11:16 * @Version: 1.0 **/ public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(this.getClass().getResource("sample.fxml")); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }