JavaFX 部署 - 图像丢失

标签 java css deployment javafx export

我使用 e(fx)clipse 在 JavaFX 中完成了一个小型私有(private)元素。现在我想将它导出为可运行的 jar 文件。一切正常,除了 Pane 和按钮背景图像丢失的事实。这些图像的路径在单独的 CSS 文件中定义。该文件中的其他定义实现良好,只是缺少图像。 知道这可能是什么原因吗?还是有更好的方法来发布完成的 Java 元素?

最佳答案

这似乎是一个普遍的问题。我自己也很挣扎。看看我是如何引用css和css中的图片的。

这是一个在开发环境、Scene Builder 和打包的 JAR 中工作的解决方案。

文件夹结构:

enter image description here

主要.java:

package application;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;


public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {

            FXMLLoader loader = new FXMLLoader(Main.class.getResource("view/RootLayout.fxml"));
            AnchorPane rootLayout = (AnchorPane) loader.load();

            Scene scene = new Scene(rootLayout, 400, 400);
            scene.getStylesheets().add(getClass().getResource("css/application.css").toExternalForm());

            primaryStage.setScene(scene);
            primaryStage.show();

        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

根布局.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.view.RootLayoutController">
   <children>
      <Pane layoutX="0.0" layoutY="0.0" prefHeight="200.0" prefWidth="200.0">
         <children>
            <Button fx:id="sunButton" layoutX="74.0" layoutY="88.0" mnemonicParsing="false" onAction="#handleSunButtonClick" styleClass="sun-button" stylesheets="@../css/toolbar.css" text="Button" />
         </children>
      </Pane>
   </children>
</AnchorPane>

RootLayoutController.java:

package application.view;

import javafx.fxml.FXML;
import javafx.scene.control.Button;

public class RootLayoutController {


    @FXML
    Button sunButton;

    @FXML
    public void handleSunButtonClick() {
        System.out.println( "Button clicked");
    }
}

工具栏.css:

.sun-button {
  -fx-graphic: url('./icons/sun.png');
}

应用程序.css:

.root {
    -fx-background-color:lightgray;
}

太阳.png:

enter image description here

这在开发环境和打包 JAR 时都有效(在 Eclipse 中选择“将所需的库提取到生成的 JAR 中”)。

屏幕截图(只是一个带有通过 css 加载的图标的按钮)

enter image description here

关于JavaFX 部署 - 图像丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28324578/

相关文章:

html - 并排渲染两里

java - 如何在JasperReport中使详细信息部分不分割

java - Spring Data JPA 何时实际调用数据库上的 INSERT?

java - 如何在 LibGDX 中绘制 BitmapFont?

css - Angular Material md-content 压缩模拟元素

javascript - 从样式设置为 % 的元素中获取以像素为单位的宽度?

java - (Java) 退出循环 "remotely"

python - 如何从 python 方法中执行 python 代码?

Azure "Deployment successful"但应用程序 URL 产生 ":( Application Error"... Docker ... 容器启动失败

c# - VS2008安装包自动包含运行时库/框架