要将CSS文件嵌入到JAR文件中并通过@CssImport
注解引用它,你需要遵循以下步骤:
styles.css
。src/main/resources
。@CssImport
注解来引用CSS文件。假设你的项目结构如下:
my-javafx-app/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/example/App.java
│ │ └── resources/
│ │ └── styles.css
└── pom.xml (for Maven)
styles.css:
.button {
-fx-background-color: #4CAF50;
-fx-text-fill: white;
}
App.java:
package com.example;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import org.openjfx.javafxplugin.annotations.CSSImport;
@CSSImport(resource = "/styles.css")
public class App extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
pom.xml (Maven配置):
<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>com.example</groupId>
<artifactId>my-javafx-app</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<!-- JavaFX dependencies -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.8</version>
<configuration>
<mainClass>com.example.App</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
通过以上步骤,你应该能够成功地将CSS文件嵌入到JAR中并通过@CssImport
注解引用它。
领取专属 10元无门槛券
手把手带您无忧上云