简体   繁体   English

如何放置JFrame图标

[英]How to put a JFrame icon

I want to set an icon for my application in Java. 我想在Java中为我的应用程序设置一个图标。 I'm using Eclipse. 我正在使用Eclipse。

I don't know if the way of storing the icon (and the config file by the way) into the project is the best one (I accept suggestions to learn the best way). 我不知道将图标(以及顺便提供的配置文件)存储到项目中的方式是最好的(我接受建议以学习最佳方法)。

Anyway I'm trying to use this line into my extended JFrame class: 无论如何,我正在尝试将此行用于我的扩展JFrame类:

setIconImage(Toolkit.getDefaultToolkit().getImage("img/icon.png"));

But doesn't work: still with the coffee cup icon. 但是不起作用:仍然带着咖啡杯图标。

How can I access to the icon into package estacionBase.img? 如何访问包含estacionBase.img的图标? Is there a better place to store it? 有没有更好的地方存放? How would I access it then? 那我怎么访问呢?

在此输入图像描述

Instead of saving your resources alongside your source files, save it outside src in a folder called something like res . 不要将资源与源文件一起保存,而是将它保存在src之外的一个名为res的文件夹中。 It's a good idea to separate your source from your resources. 将源与资源分开是个好主意。

As for the icon, use setIconImage(ImageIO.read("res/icon.png")); 至于图标,请使用setIconImage(ImageIO.read("res/icon.png"));

However: 然而:

If your icons are inside a jar , you'll have to use ImageIO.read(Classname.class.getResource("res/icon.png")); 如果你的图标在jar ,你将不得不使用ImageIO.read(Classname.class.getResource("res/icon.png"));

I think that's right, however take care with your relative paths and if it's not working, the first thing to check would the your paths relative to where it's being executed from (whether that's from the .class dirs or from a jar at some stage). 我认为这是正确的,但要注意你的相对路径,如果它不起作用,首先要检查你的路径相对于它的执行位置(无论是来自.class dirs还是来自某个阶段的jar) 。

For the saving issue: Create a new source folder in your project and call it res or so. 对于保存问题:在项目中创建一个新的源文件夹并将其称为res左右。 Then you can put your ressources in there. 然后你可以把你的资源放在那里。 As res is marked as a source folder, it will be in your jar as well. 由于res被标记为源文件夹,它也将在你的jar中。

For the loading, you can use 对于加载,您可以使用

setIconImage(ImageIO.read("res/icon.png"));

or 要么

setIconImage(
    new ImageIcon(getClass().getResource("res/icon.png"), description).getImage()
);

Of course, it is also ok to have the images in between your source code. 当然,在源代码之间插入图像也是可以的。 Most of the official Java demo's (for instance here ) do it that way. 大多数官方Java演示(例如这里 )都是这样做的。 It's more compact. 它更紧凑。 I wouldn't use that technique for larger projects though. 我不会将这种技术用于大型项目。 It can get quite messy. 它会变得非常混乱。

Try to put your image into a second folder such as /res as other people suggested then use the code: 尝试将您的图像放入第二个文件夹,如其他人建议的/ res,然后使用代码:

setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("path/to/icon.png")));
I tried this for my applications and it worked every time. 我为我的应用程序尝试了这个,每次都有效。 Also, try not to put the image into a package as well. 另外,尽量不要将图像放入包中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM