2013-04-06 15 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