项目结构
. ├── pom.xml └── src ├── main │ ├── java │ │ └── com │ │ └── pengshiyu │ │ ├── Controller.java │ │ └── Main.java │ └── resources │ ├── fxml │ │ └── sample.fxml │ └── style │ └── main.css └── test └── java
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>demo</artifactId> <version>1.0-SNAPSHOT</version> <build> <plugins> <!-- 运行javaFX--> <plugin> <groupId>com.zenjava</groupId> <artifactId>javafx-maven-plugin</artifactId> <version>8.8.3</version> <configuration> <mainClass>com.pengshiyu.Main</mainClass> </configuration> </plugin> <!-- 构建javaFX成jar--> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.1.1</version> <configuration> <archive> <manifest> <!-- 指定程序入口--> <mainClass>com.pengshiyu.Main</mainClass> </manifest> </archive> </configuration> </plugin> </plugins> </build> </project>
src/main/java/com/pengshiyu/Main.java
package com.pengshiyu; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception{ Parent root = FXMLLoader.load(getClass().getResource("/fxml/sample.fxml")); primaryStage.setTitle("Demo"); primaryStage.setScene(new Scene(root, 600, 600)); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
src/main/java/com/pengshiyu/Controller.java
package com.pengshiyu; import javafx.scene.control.Label; public class Controller { public Label label; public void clickButton(){ label.setText("按钮被点击了"); System.out.println("按钮被点击了"); } }
src/main/resources/fxml/sample.fxml
<?xml version="1.0" encoding="UTF-8"?> <?import javafx.geometry.Insets?> <?import javafx.scene.layout.GridPane?> <?import javafx.scene.control.Button?> <?import javafx.scene.control.Label?> <GridPane fx:controller="com.pengshiyu.Controller" stylesheets="/style/main.css" xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10"> <Button mnemonicParsing="false" onAction="#clickButton" text="按钮" /> <Label fx:id="label" layoutX="10"/> </GridPane>
src/main/resources/style/main.css
.label{ -fx-text-fill: red; }
指令
# 运行程序 mvn clean jfx:run # 生成jar文件 mvn package
项目截图