Gluon Scene Builder 11中Icon组件显示异常问题求助
问题
我正在开发一个JavaFX桌面应用,使用Java 13、JavaFX 15和SceneBuilder 11。已按照openjfx官网中「JavaFX and Intellij -> Non-modular with Gradle」指南完成Gradle项目配置。配置完成后,在SceneBuilder中打开.fxml文件,从Gluon子菜单添加Icon组件并设置样式,但运行应用时显示矩形而非所选Icon。
以下是我的Gradle配置文件和.fxml文件:
Gradle配置文件
plugins { id 'application' id 'org.openjfx.javafxplugin' version '0.0.8' } repositories { maven { url 'https://nexus.gluonhq.com/nexus/content/repositories/releases/' } mavenCentral() } dependencies { implementation 'com.gluonhq:charm-glisten:6.0.5' } javafx { version = "15.0.1" modules = ['javafx.controls', 'javafx.fxml'] } mainClassName = 'org.stoicescu.MainApp'
.fxml文件
<?xml version="1.0" encoding="UTF-8"?> <?import com.gluonhq.charm.glisten.control.Icon?> <?import javafx.scene.layout.BorderPane?> <?import javafx.scene.layout.HBox?> <BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="org.stoicescu.FXMLController"> <top> <HBox prefHeight="40.0" prefWidth="600.0" BorderPane.alignment="CENTER"> <children> <Icon content="ASSISTANT_PHOTO" prefHeight="40.0" prefWidth="40.0" style="-fx-background-color: green;"/> </children> </HBox> </top> </BorderPane>
可能的原因与解决方案
我之前也碰到过类似的问题,主要是Gluon Charm的Icon组件依赖特殊资源才能渲染,结合你的配置来看,大概率是这几个点出了问题:
1. 缺失图标字体依赖
Charm Glisten的Icon组件需要配套的charm-glisten-fonts库,这个库包含了渲染图标必需的字体文件。你的Gradle依赖里只引入了charm-glisten,没有包含字体库,导致运行时找不到图标对应的字体,只能显示空白矩形。
解决方法:在dependencies块中添加字体依赖,注意版本要和charm-glisten保持一致:
implementation 'com.gluonhq:charm-glisten-fonts:6.0.5'
2. 未初始化Charm资源
有时候即使添加了依赖,字体也可能没被正确加载。你可以在应用启动时手动初始化Charm的资源,确保字体被加载:
import com.gluonhq.charm.glisten.application.MobileApplication; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class MainApp extends Application { @Override public void start(Stage stage) throws Exception { // 初始化Charm资源,包含字体加载 MobileApplication.getInstance().init(); FXMLLoader loader = new FXMLLoader(getClass().getResource("/org/stoicescu/main.fxml")); Parent root = loader.load(); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
3. 检查版本兼容性
确认SceneBuilder使用的Charm版本和你项目依赖的版本一致。SceneBuilder可能自带了某个版本的Charm资源,所以能预览图标,但运行环境用的是另一个版本,可能存在图标常量不匹配的情况。
4. 验证图标常量正确性
确认ASSISTANT_PHOTO是Charm Glisten 6.0.5版本中存在的图标常量。可以查阅对应版本的文档,或者用代码枚举可用的图标值,避免拼写错误。
最后,同步Gradle依赖、清理并重新构建项目,再运行应该就能看到正确的图标了。
内容的提问来源于stack exchange,提问作者iulian16




