简体   繁体   English

将ImageIcon添加到JTabbedPane

[英]Adding ImageIcon to JTabbedPane

I am attempting to add a picture to the first tab of a JTabbedPane, here is my code: 我试图将图片添加到JTabbedPane的第一个标签中,这是我的代码:

JTabbedPane application = new JTabbedApplication();
JPanel welcomePanel = new JPanel();
JLabel imageLabel = new JLabel(new ImageIcon("track.jpg"));
welcomePanel.add(imageLabel);
application.addTab("WELCOME", welcomePanel);
application.setMnemonicAt(0, KeyEvent.VK_1);

The image file is located in the same location as the class this code is in. For some reason, however, my image is not appearing. 该图像文件与该代码所在的类位于相同的位置。但是由于某种原因,我的图像没有出现。 I have used the same JLabel and used text instead of an image and it appears. 我使用了相同的JLabel,并使用了文本而不是图像,它出现了。 Can someone give me some insight into this problem? 有人可以给我一些有关这个问题的见解吗?

Java doesn't know that the image is located directly beside the running class file. Java不知道该图像直接位于正在运行的类文件旁边。 You have to hand in the absolute path. 您必须交出绝对路径。 Which means Path + filename. 这意味着路径+文件名。

This little piece of code will help you to tell Java that the image is in the current working directory. 这小段代码将帮助您告诉Java该映像位于当前工作目录中。

String file = new File("track.jpg").getAbsolutePath();

Added to your code snipped it looks like this: 添加到您的代码片段中,它看起来像这样:

JTabbedPane application = new JTabbedPane();
JPanel welcomePanel = new JPanel();
String file = new File("track.jpg").getAbsolutePath();

JLabel imageLabel = new JLabel(new ImageIcon(file));
welcomePanel.add(imageLabel);
application.addTab("WELCOME", welcomePanel);

The image file is located in the same location as the class this code is in 图像文件与该代码所在的类位于相同的位置

Instead of JLabel imageLabel = new JLabel(new ImageIcon("track.jpg")); 代替JLabel imageLabel = new JLabel(new ImageIcon("track.jpg")); which is looking for a file in the current working directory, you should be using Class#getResource which will return a URL to the embedded resource. 如果要在当前工作目录中查找文件,则应使用Class#getResource ,它将返回URL到嵌入式资源。

It's important to note, that resources which are store within the application context (ie embedded inside the Jar or within the source packages) aren't accessible as "files" anymore. 重要的是要注意,存储在应用程序上下文中的资源(即嵌入在Jar或源程序包中的资源)不再可以作为“文件”访问。

Instead, you could try using something like... 相反,您可以尝试使用类似...

ImageIcon icon = new ImageIcon(ImageIO.read(getClass().getResource("track.jpg"));

to load the image. 加载图像。 Unlike ImageIcon , ImageIO.read will throw an IOException if the image can't be read, which is always more useful than the silence that you get from ImageIcon ImageIcon不同,如果无法读取图像,则ImageIO.read将引发IOException ,这总是比从ImageIcon获得的静音有用。

If this fails to work, more context on the structure of your app will be needed 如果此操作不起作用,则将需要有关应用程序结构的更多上下文

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

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