JavaFX控件ID:设置Label文本内容代码示例
作者:互联网
最终效果
点击按钮后label文本会发生变化:
设置label的ID:fx:id
:
自动生成属性:
pom
<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>
fxml
<?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>
java代码
Controller
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);
}
}
标签:控件,示例,javafx,JavaFX,scene,fxml,Controller,import,public 来源: https://blog.51cto.com/u_7692005/2967917