我正在尝试让我的面板显示图像作为背景。我已经可以在 NetBeans 中做到这一点,但是当我构建我的 jar 并运行它时,图像并没有显示在那里。我知道我必须以不同的方式访问它。我看过很多教程,但每个教程都展示了如何使用 ImageIcon 来完成,但我不需要那个,我只需要 Image。谁能指出我需要哪段代码来做到这一点?谢谢。
这是我的后台 JPanel 代码:
public class JPanelWB extends JPanel { // Creates JPanel with given image as background.
private Image backgroundImage;
public JPanelWB(String fileName){
try {
backgroundImage = ImageIO.read(new File(fileName));
} catch (IOException ex) {
new JDialog().add(new Label("Could not open image."+ex.getMessage()));
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw the background image.
g.drawImage(backgroundImage, 0, 0, getWidth(),getHeight(),this);
}
}