2013-04-06 14 views
1

我想加载图像并设置为背景,但我在selectionPanel方法“无法加载背景图像”时出现错误。加载图像设置背景时出错

看来图像处理出了问题,但我找不出什么。

public class selectionPanel extends JPanel 
{ 
    //Variable with the name of our pic 
    private static final String path = "selbkgrnd.jpg"; 
    private ImageIcon imageIcon; 
    private Dimension windowSize; 
    private int imageHeight; 
    private int imageWidth; 

    protected selectionPanel() 
    { 

    this.imageIcon = new ImageIcon("selbkgrnd.jpg"); //Save image to imageIcon 
    Image image = this.imageIcon.getImage(); 
    this.imageWidth = image.getWidth(null); 
    this.imageHeight = image.getHeight(null); 
    if ((this.imageWidth == -1) || (this.imageHeight == -1)) //Check if background image is succesfully loaded 
    { 
     JOptionPane.showMessageDialog(JOptionPane.getDesktopPaneForComponent(this), "Could not load background image", "Fatal error!", 0); 

     System.exit(-1); 
    } 
    this.windowSize = new Dimension(this.imageWidth, this.imageHeight); 
    } 

    protected void startScreen() 
    { 
    setOpaque(false); 
    setSize(this.windowSize); 
    } 

    protected int getImageHeight() 
    { 
    return imageHeight; 
    } 

    protected int getImageWidth() 
    { 
    return imageWidth; 
    } 

    @Override 
    public void paintComponent(Graphics g) 
    { 
    g.drawImage(this.imageIcon.getImage(), 0, 0, null); 
    super.paintComponent(g); 
    } 
} 

回答

0

通常这是由于您在图像文件的位置错误。尝试使用到图像的完整路径,要么或相对于用户的目录的路径可以与发现:

System.out.println("user directory: " + System.getProperty("user.dir")); 

编辑
幽州:

谢谢你,它的工作与完整的路径,但它不应该只与图像名称,如果它在源代码文件夹内?

不需要.Java将再次查找与用户目录相关的文件。

但是请注意,如果图像位于类文件目录或相对于此目录的目录中,并且您创建了一个jar文件并且需要访问这些图像,则无法使用文件。您需要将图像作为资源,并且相对路径将为不同,因为它不会与user.dir相关,而是相对于类文件的位置。

+0

该图像位于源代码文件夹内。我会尝试你所说的。 – Manos 2013-04-06 16:05:37

+0

谢谢它与完整路径一起工作,但它不应该只与图像名称一起使用,如果它在源代码文件夹内? – Manos 2013-04-06 16:14:19

+0

@mkontakis:请参阅编辑。 – 2013-04-06 16:46:35