如果我使用以下代码访问我的图像,那么整个项目在eclipse上运行并以Jar形式执行:
BufferedImage myPicture;
BufferedImage myPicture2;
try {
myPicture= ImageIO.read(new File("button1.jpg"));
myPicture2 = ImageIO.read(new File("button2.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
但是,如果我用以下代码替换上面的代码,那么整个项目在eclipse上运行但是不能作为Jar执行,它不会响应双击:
myPictureurl = getClass().getResource("button1.jpg");
myPictureurl2 = getClass().getResource("button2.png");
icon = new ImageIcon(myPictureurl);
icon2 = new ImageIcon(myPictureurl2);
// icon to bufferedimage
myPicture = new BufferedImage(
icon.getIconWidth(),
icon.getIconHeight(),
BufferedImage.TYPE_INT_RGB);
//
myPicture2 = new BufferedImage(
icon2.getIconWidth(),
icon2.getIconHeight(),
BufferedImage.TYPE_INT_RGB);
//
Graphics gg = myPicture.createGraphics();
icon.paintIcon(this, gg, 0,0);
gg.dispose();
Graphics g2 = myPicture2.createGraphics();
icon2.paintIcon(this, g2, 0,0);
g2.dispose();
注意:获取BufferedImage后,我用它来绘制CustomButton:
/**
* paints the CustomButton
*/
@Override
public void paint(Graphics g) {
g.drawImage(myPicture, 0, 0, 200, 25, this);
if (pressed) {
g.setColor(getBackground().darker().darker());
g.drawImage(myPicture2, 0, 0, 200, 25, this);
} else {
g.setColor(getBackground());
}
为什么最后一个代码禁止执行jar?
实际上,
1)我在这一行得到一个NullPointerException:
icon = new ImageIcon(myPictureurl);
我的图像放在主应用程序文件夹,src文件夹和bin文件夹中:
“button1.png”
“button2.png”
我发布的第二个代码块适用于我项目中的其他图像资源。
2)和我的“config.properties”加载方法的FileNotFoundException:
try {
prop.load(new FileInputStream("config.properties"));
} catch (IOException ex) {
ex.printStackTrace();
}
更新
由于没有明显的原因,一个试用罐加载图像很好,但我不能再制作另一个。