我使用了一个类Imagepanel来显示背景图像到我的netbeans面板。当它从IDE netbeans 6.8运行时成功工作,但是当我从jar文件中运行它时它不显示图像。请帮助我解决这个问题。谢谢你的评论。这是我的代码imageppanel。java
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
class ImagePanel extends JPanel {
private Image img;
public ImagePanel(String img ) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(this.getMaximumSize());
setMinimumSize(size);
setMaximumSize(size);
setSize(this.getMaximumSize());
setLayout(null);
}
@Override
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
我已经创建了我的面板,它在另一个类中,我的图像在src下的目录images中。提前谢谢。
ImagePanel pan2 = new ImagePanel("src/images/tarif.png");
import java.awt.*;
import javax.swing.*;
class BackgroundPanel extends JPanel
{
Image image;
public BackgroundPanel(String path)
{
try
{
image = (new ImageIcon(getClass().getResource(path))).getImage();
}
catch(Exception e){/*handled in paintComponent()*/}
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
这段代码工作了,我像这样调用这个类
String path ="/images/tarif.png";
JPanel pan2=new BackgroundPanel(path);