2012-07-23 8 views
0

我想爲我的java類做最後的項目。我正在嘗試使用.png圖片並將其用作可添加到我的JFrame中的組件。但是,當我嘗試這樣做時,它會引發異常並執行catch語句中的內容。我不明白爲什麼它會這樣做。我在與.java文件相同的文件夾中有.png文件。圖像作爲組件問題

package InventoryApp; 

import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 
import javax.imageio.ImageIO; 
import javax.swing.ImageIcon; 
import javax.swing.JButton; 
import javax.swing.JLabel; 

/** 
* 
* @author Curtis 
*/ 
public class FinalProject extends DFrame 
{ 
//main method 
public static void main(String[] args) 
{ 
    start(); 
} 

//building splash screen 

public static void start() 
{ DFrame splashFrame = new DFrame(); 
    try 
    { 
    BufferedImage myPicture = ImageIO.read(new File("logo.png")); 
    JLabel picLabel = new JLabel(new ImageIcon(myPicture)); 
    splashFrame.add(picLabel); 
    } 
    catch(IOException g) 
    { 
     JLabel error = new JLabel("Picture Could Not Be Found"); 
     splashFrame.add(error); 
    } 


    JButton create = new JButton("Click to Create Item List"); 
    JButton view = new JButton("Click to View Item List"); 
    splashFrame.add(create); 
    splashFrame.add(view); 


} 

} 
+0

什麼是例外? – MadProgrammer 2012-07-23 02:10:04

+0

你能否詳細說明我如何解決這個問題?當我試圖抓取文件時,我認爲它拋出了異常。 – 2012-07-23 02:13:51

+0

在異常塊中,您需要打印異常。基本上你可以調用'g.dumpStackTrace()'來獲得一個快速和髒的轉儲 – MadProgrammer 2012-07-23 02:17:49

回答

1

當你創建一個沒有指定路徑的File對象,它假定程序從啓動目錄,目錄中的當前類文件是在你可能想改用FinalProject.class.getResource()

BufferedImage myPicture = ImageIO.read(FinalProject.class.getResource("logo.png")); 
+0

你能幫我這個代碼嗎?我得到一個錯誤BufferedImage myPicture = ImageIO.read(new File(FinalProject.class.getResource(「logo.png」))); – 2012-07-23 02:17:04

+1

對不起,我的意思是你可以完全省略'File',並使用帶有URL的'ImageIO.read()'版本。 – 2012-07-23 02:18:46

+0

感謝您的協助。 – 2012-07-23 02:35:16