简体   繁体   English

如何使用imageicon(Java GUI)将图像添加到JPanel?

[英]How do I add an image to JPanel using imageicon (Java GUI)?

I looked all over the place but I am still stuck on how directory works to find the image to put onto the JPanel. 我环顾四周,但仍然停留在目录如何工作以查找要放在JPanel上的图像上。 Where is the image supposed to be? 图像应该在哪里? I clicked on properties for my image and it shows Location: C:\\Users\\Joseph\\Pictures\\Background and the picture's name is random.jpg . 我单击了图像的属性,它显示位置: C:\\Users\\Joseph\\Pictures\\Background并且该图像的名称为random.jpg

I am trying to add an image to a tab using tabbedPane. 我正在尝试使用tabbedPane将图像添加到选项卡。 Here is what I have so far, and I am not able to do it. 到目前为止,这是我所能做的,但我无法做到。

JPanel flPanel = new JPanel();

flPanel.setLayout(new FlowLayout());

ImageIcon image = new ImageIcon(getClass().getResource("")); 
// Tried /Users/Joseph/Pictures/Background/random.jpg and doesn't work

JLabel j1 = new JLabel(image);

flPanel.add(j1);

tabbedPane.add("Tab 2", flPanel);

Is the picture supposed to be in the same package file as the project? 图片是否应该与项目位于同一包文件中? Or is it supposed to be in the source file to be able to just do "random.jpg"? 还是应该能够在源文件中执行“ random.jpg”?

If you want the image to be available to your application at runtime, then you should consider making sure that the image is included within your Jar when you application is built. 如果希望在运行时将图像提供给应用程序,则应考虑在构建应用程序时确保该图像包含在Jar中。

From the sounds of it, you are using Netbeans, you should copy the image to a directory within your src directory of your project. 从声音上看,您正在使用Netbeans,应该将映像复制到项目的src目录中的目录中。

You should then be able to use... 然后,您应该可以使用...

BufferedImage bi = ImageIO.read(getClass().getResource("/full/path/to/image/random.jpg"));
ImageIcon image = new ImageIcon(bi);

The path to the image should be the full path (from the context of the src directory) within your project. 图像的路径应该是项目中的完整路径(来自src目录的上下文)。

That is, if you placed the image in the resources directory within the src directory, then you would use /resources/random.jpg as the path/file name 也就是说,如果将图像放置在src目录中的resources目录中,那么将使用/resources/random.jpg作为路径/文件名。

Take a look at Reading/Loading an Image for more details 看看阅读/加载图像的更多细节

getClass().getResource(...) will only get resources inside the classpath. getClass()。getResource(...)将仅在类路径中获取资源。

You can use ImageIO.read(File) like this: 您可以像这样使用ImageIO.read(File):

BufferedImage bi = ImageIO.read(new File("C:\\Users\\Joseph\\Pictures\\Background\random.jpg"))
ImageIcon image = new ImageIcon(bi);

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

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