使用资源文件夹通过IntelIiJ在JavaFX项目上加载图像 [英] Using a resource folder to load images on JavaFX project using IntelIiJ

查看:103
本文介绍了使用资源文件夹通过IntelIiJ在JavaFX项目上加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像加载到JavaFX项目.我通过调用绝对路径Users/user/Desktop/nfc.png来做到这一点.有什么方法可以在项目内部创建资源文件夹并从中调用图像吗?

I'm trying to load an image to a JavaFX project. I'm doing it by calling the absolute path Users/user/Desktop/nfc.png. Is there any way to create a resource folder inside the project and calling from it the image?

下面是我的代码:

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;

import java.awt.Taskbar;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;



public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));

        primaryStage.setResizable(false);

        Scene scene = new Scene(root);

        scene.getStylesheets().add("/sample/desing.css");

        primaryStage.getIcons().add(new Image("file:/Users/user/Desktop/nfc.png "));



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


    public static void main(String[] args)
    {
        Taskbar taskbar=Taskbar.getTaskbar();
        BufferedImage image = null;
        try {
            image = ImageIO.read(new File("/Users/user/Desktop/nfc.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        taskbar.setIconImage(image);
        launch(args);
    }
}

我正在使用IntelIJ.我尝试通过在项目目录上创建一个名为resource的文件夹并将其命名为Main.class.getResource()

I'm using IntelIJ. I've tried by creating a folder named resource on the project directory and call the image Main.class.getResource()

推荐答案

查找图片的快速解决方案

您将看到如何通过提供字符串"/sample/desing.css"在上一行中加载样式表,对图像执行相同的操作,例如new Image("/sample/nfc.png").

You see how you load the stylesheet in the preceding line by providing the string "/sample/desing.css", do the same thing for your image, e.g. new Image("/sample/nfc.png").

假定图像与CSS位于同一位置.如果在其他地方,例如在/images/ngc.png下,那么您将使用该路径.它还假定已将构建系统配置为将源资源文件复制到项目输出目录.

That assumes that the image is in the same location as your css. If it were somewhere else, e.g. under /images/ngc.png, then you would use that path. It also assumes that your build system is configured to copy the source resource files to your project output directory.

当您的项目基于构建工具(例如maven)时查找图像

如果您使用的是Maven或Gradle之类的构建工具(建议用于任何中型或大型项目),它将具有

If you are using a build tool such as Maven or Gradle (recommended for any medium to large size project), it will have a standard structure where your java classes are in src/main/java and your resources, such as css and images are in src/main/resources. It is automatically configured to copy the resources into your application artifact.

使用IntelliJ或其他IDE查找图像

您注意到您正在使用IntelliJ,该工具(和任何其他主要的Java IDE)足够智能,可以识别使用诸如maven之类的构建工具构建的项目具有标准结构,并会自动在其中配置导入的maven项目.了解该结构的想法,因此您无需执行任何其他操作.

You note that you are using IntelliJ, that tool (and any other major Java IDE) is intelligent enough to recognize that a project built with a build tool such as maven has a standard structure and will automatically configure an imported maven project in Idea to understand that structure, so you don't have to do anything additional.

如果您未使用推荐的工具(例如maven),则可以手动配置项目以复制资源(如 @egimaben在他的答案中定义).在其他IDE中复制资源的手动配置会有所不同,因此您需要研究IDE如何处理项目资源,以找出如何在此类项目中执行此操作.

If you are not using a recommended tool such as maven, then you can configure the project manually to copy over resources (as @egimaben defined in his answer). Manual configuration for copying resources in other IDEs will differ, so you will need to research how the IDE handles project resources to work out how to do that for such projects.

查找图片的示例代码

例如,如果图像位于项目源:src/main/resources/images/ngc.png中的此位置,则可以通过以下方式在项目中访问它:

So for example, if your image is in this location within your project source: src/main/resources/images/ngc.png, you can access it in your project via:

Image image = new Image("/images/nfc.png");

如果不需要引用图像,则可以直接从ImageView构造函数中引用位置:

If you don't need a reference to the image, you can just directly reference the location from your ImageView constructor:

ImageView imageView = new ImageView("/images/nfc.png");

相关文档

阅读

Read the image doc to see how images are found. Specifically, these lines show how to load images from resources on the class path:

// The image is located in default package of the classpath
Image image1 = new Image("/flower.png", true);

// The image is located in my.res package of the classpath
Image image2 = new Image("my/res/flower.png", 100, 150, false, false);

有关明确使用file:协议的注意事项(请勿这样做)

Note on explicitly using the file: protocol (don't do it)

要从类或模块路径加载,请不要显式使用file:协议,您的文件可能位于jar或其他位置,例如在远程网络上,因此访问它们所需的协议可能会发生变化(需要使用

To load from the class or module path, don't explicitly use the file: protocol, your files could be in a jar or elsewhere such as on a remote network, so the protocol needed to access them could change (a file in jar needs to be accessed using the jar: protocol, not the file: protocol). When you don't specify a protocol in your Image constructor, then the system will default to use the class loader, which already knows what protocol to use to find resources on your class path.

问题排查

在您要加载图像的代码中放置以下行:

Place the following line in your code where you are trying to load the image:

System.out.println(getClass().getResource("<imagepath>"))

"<imagepath>"的位置与您传递给图像构造器的字符串完全相同.如果调用输出null,则图像可能不在您预期的位置的类路径上.

Where is the "<imagepath>" is exactly the same string you passed to the image constructer. If the call outputs null, then the image is probably not on your class path at the expected location.

如果您的应用程序打包为jar,请运行jar tvf <yourjar>.jar,将<yourjar>替换为jar文件的名称,它将列出jar文件中的所有内容.图像很可能不在您尝试从中检索的jar文件中的位置,因此您将需要移动图像或修复构建系统以将其放置在正确的位置.

If your app is packaged as a jar, run jar tvf <yourjar>.jar, replacing <yourjar> with the name of your jar file and it will list everything in the jar file. Most likely the image won't be at the location in the jar file you are trying to retrieve it from, so you will need to move it around or fix your build system to get it in the right place.

图片出现错误例外属性,如果无法加载,则可以查询该异常,它可以为您提供更多有关发生问题的信息,例如:

Image has error and exception properties, if it fails to load, you can query the exception and it may provide you with some more info on what went wrong, e.g.:

Image image = new Image("/images/nfc.png");
if (image.isError()) {
    System.out.println(image.getException());
}

如果您使用

If you use an image constructor with background loading, then the error could occur asynchronously, so you would need to monitor changes in the error property to know if an error occurred:

Image image = new Image("/images/nfc.png");
if (image.isError()) {
    System.out.println(image.getException());
} else {
    image.errorProperty().addListener((observable, oldValue, newValue) -> {
        if (image.isError()) {
            System.out.println(image.getException());
        }
    });
}

这篇关于使用资源文件夹通过IntelIiJ在JavaFX项目上加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆