如何在项目文件夹的jlabel上设置图像? [英] How to set image on jlabel from project folder?

查看:88
本文介绍了如何在项目文件夹的jlabel上设置图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作Java桌面应用程序.

I am trying to make a Java desktop application.

我想在JLabel上设置图像.

我正在使用NetBeans.

I am using NetBeans.

在我的项目文件夹中,我的目录结构是:

From my project folder, my directory structure is:

F:/>MARKET
    |
    |___src
    |
    |___lib
    |
    |___src
    |      |
    |      |__defaultpackage
    |                       |
    |                       demo.java
    |__images
            |
            |
            Logo1.png

我使用了以下代码:

jLabel4 = new JLabel(new ImageIcon("images/Logo1.png"));

它不起作用,如何获得我的输出?

It is not working, how can I get my output?

推荐答案

如果要将图像包含在Jar中,则需要将images文件夹移动到src目录中.

If you want the images included within the Jar, then you will need to move the images folder into the src directory.

然后这将要求您使用更多类似...

This will then require you to use something more like...

jLabel4 = new JLabel(new ImageIcon(getClass().getResource("/images/Logo1.png")));

到加载图像.

如果您希望图像保留在程序Jars的外部(并保持对文件系统的打开状态),则需要确保程序的执行上下文在项目文件夹的上下文内(处于同一级别)作为srcimages目录).

If you want the images to remain external to your program Jars (and remain open to the file system), then you need to ensure that the execution context for the program is within the context of the project folder (at the same level as the src and images directory).

这可以通过项目属性->运行属性来完成.默认情况下,运行时,程序将从运行的项目文件夹的上下文中执行.

This can be done via the Project Properties -> Run properties. By default, when run, the program will execute from the context of the running projects folder.

如果您想使用外部资源,可以做两件事来检查它们...

If you're wanting to use external resources you can do two things to check for them...

一个,使用与要加载的外部资源相同的路径创建一个File,并检查其是否存在...

One, create a File using the same path as the external resource you want to load and check to see if it exists...

 if (new File("images/Logo1.png").exists()) {...

或者,如果您似乎无法使其正常工作,请使用...检查当前运行的上下文.

Or if you can't seem to get it to work, check your current running context with...

System.out.println(new File(".").getCanonicalPath());

这将告诉您当前的工作目录(请注意,这将抛出IOException).

Which will tell your current working directory (beware this will throw an IOException).

您还可以使用系统属性user.dir

You can also use the system property user.dir

System.out.println(System.getProperty("user.dir"));

这篇关于如何在项目文件夹的jlabel上设置图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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