javafx访问jar外面的图片


Jacob
2025-03-15 12:32:56 (6天前)


我很难在罐子外面访问图像源。
我正在为画布加载图像,当图像位于jar内时,该画布没有问题。

但现在我想创造……

2 条回复
  1. 0# 晴天 | 2019-08-31 10-32



    你应该只能使用相对路径

    File

    宾语:




    1. File imageFile = new File(“images/picture.png”)

    2. </code>


    您的

    program.jar

    将从基目录开始;在创建时

    File

    object,这是您要传递给构造函数的路径的起点。因此,

    new File(“images/picture.png”)

    将在“images”子目录中查找pictures.png文件。



    获得该文件后,您将需要创建自己的文件

    Image

    使用该文件的URI:




    1. Image image = new Image(imageFile.toURI().toString());

    2. </code>


    这实际上创建了文件的完整绝对路径。





    样品申请:
    </强>




    这是一个你可以尝试自己的简单例子。你需要确保你拥有

    resources

    在输出文件夹(.jar文件所在的位置)中创建的文件夹,以及其中的合适图像文件。




    1. import javafx.application.Application;
      import javafx.fxml.FXMLLoader;
      import javafx.geometry.Insets;
      import javafx.geometry.Pos;
      import javafx.scene.Parent;
      import javafx.scene.Scene;
      import javafx.scene.image.Image;
      import javafx.scene.image.ImageView;
      import javafx.scene.layout.VBox;
      import javafx.stage.Stage;

    2. import java.io.File;

    3. public class Main extends Application {

    4. @Override
    5. public void start(Stage primaryStage) throws Exception{
    6.     // Just a box to put our image in
    7.     VBox root = new VBox();
    8.     root.setPadding(new Insets(10));
    9.     root.setAlignment(Pos.CENTER);
    10.     // Create our image. It is located in the "resources" folder of our application. We will first create a File
    11.     // to represent the external resource.
    12.     File imageFile = new File("resources/icon.png");
    13.     Image image = new Image(imageFile.toURI().toString());
    14.     // Add our image/ImageView to the scene
    15.     root.getChildren().add(new ImageView(image));
    16.     primaryStage.setTitle("External Images");
    17.     primaryStage.setScene(new Scene(root, 300, 275));
    18.     primaryStage.show();
    19. }
    20. public static void main(String[] args) {
    21.     launch(args);
    22. }
    23. }

    24. </code>




    无论是在IDE中运行应用程序还是在构建JAR或JavaFX应用程序之后,这都将起作用。


登录 后才能参与评论