用的Java Swing桌面

问题描述:

我已经创建了的Java Swing GUI和想根据我的模块创建一个自定义工具栏自定义工具栏。以下是图像我想要使用:用的Java Swing桌面

enter image description here

这些图像被放置在相同的水平我的应用程序内的src文件夹。我知道,我也许可以创建这些图像的罐子,这样我可以很容易地从我的应用程序中访问他们,但不知道怎么办。我花了数小时试图做这项工作。

下面是我的GUI,我创建的广告想用这些图像的工具栏美化别人创建标签将充当导航但是这两种方式我无法得到它的工作的数组。下面

enter image description here

的代码是我在这最后的尝试:

JToolBar toolbar1 = new JToolBar(); 

ImageIcon client = new ImageIcon("clients.png"); 
ImageIcon timesheet = new ImageIcon("timesheets.png"); 

JButton clientTB = new JButton(client); 
JButton timesheetTB = new JButton(timesheet); 

toolbar1.add(clientTB); 
toolbar1.add(timesheetTB); 

add(toolbar1, BorderLayout.NORTH); 

我甚至感动这些图像,放在他们的呼唤它们的类内。

什么可能我是做错了,请帮助?

你看看的JavaDoc ImageIcon(String),该String值是“字符串指定文件名或路径”

这是一个问题,因为你的图像是不实际的文件,更多的,他们已经嵌入您的应用程序(通常在生成的JAR文件)内,不再像“正常文件”处理。

相反,你需要使用哪个Class#getResource搜索应用程序的类路径命名资源,像...

// This assumes that the images are in the default package 
// (or the root of the src directory) 
ImageIcon client = new ImageIcon(getClass().getResource("/clients.png")); 

现在,我有一个个人的厌恶ImageIcon,因为它不会告诉你当图像由于某种原因被加载时,例如无法找到或者格式不正确。

相反,我会使用ImageIO读取图像

ImageIcon client = new ImageIcon(ImageIO.read(getClass().getResource("/clients.png"))); 

这将做两件事情,第一,它会抛出一个IOException如果图像无法加载由于某种原因而二,它直到图像完全加载才会返回,这很有帮助。

更多细节

+0

感谢@MadProgrammer这个工作就像一个魅力见Reading/Loading an Image ..... :-)我现在是一个快乐扫平。 :d – Maximum86

+0

很高兴它可以帮助;) – MadProgrammer