2014-12-03 7 views
0

이 게임의 배경 그림을로드하려고하는데 파일이 클래스 파일과 동일한 폴더에 있고 폴더가 하나뿐입니다. 파일을 참조하는 여러 가지 방법을 모색했지만 모두 실패했습니다. 이 던진 오류입니다 :NullPointerException 파일을로드하는 중 오류가 발생했습니다.

Exception in thread "main" java.lang.NullPointerException 
    at javax.swing.ImageIcon.<init>(Unknown Source) 
    at ThrustR.<init>(ThrustR.java:28) 
    at ThrustR.main(ThrustR.java:35) 

그리고 여기에 코드입니다 :

public class ThrustR extends JFrame 
{ 
    public String path; 
    public File file; 
    public BufferedImage image; 

    public void setValues() throws IOException 
    { 
     path = "CityRed.jpg"; 
     file = new File(path); 
     image = ImageIO.read(file); 
    } 

    public ThrustR(String title) 
    { 
     super(title); 

     JLabel back = new JLabel(new ImageIcon(image)); 

    } 

    public static void main(String[] args) 
    { 
     // Main Window 
     ThrustR frame = new ThrustR("ThrustR"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(720,480); 
     frame.setVisible(true); 

    } 
} 
+0

경로 = "CityRed.jpg"; HDD, 자바 패키지, BufferedImage에 유효한 경로를 리턴하지 못한다면 NullPointerException이 발생한다. 자바 패키지에 대한 오라클 튜토리얼 – mKorbel

답변

0

으로 시도 :

getClass().getResource("/CityRed.jpg") 
0

당신은 어디에서 setValues() 메소드를 호출하지 않습니다. 프로그램의 실행은 당신이 당신의 클래스 ThrustR frame = new ThrustR("ThrustR");의 객체를 생성하는 main() 방법에 간다 시작하고 그것이

public ThrustR(String title){ 
    super(title); 
    JLabel back = new JLabel(new ImageIcon(image)); 
} 

그리고에서이다 생성자의 호출 할 때 나는 밖으로 만들 수있는 것

이며, 이것은 ImageIcon 즉 new ImageIcon(image)의 또 다른 객체를 만들고 있습니다.이 순간에 image은 null이됩니다. setValues()이 지금까지 호출되지 않았으므로 기본적으로 public BufferedImage image;은 null입니다.

0

setvalues ​​() 메소드를 호출하지 않았습니다. 나는 당신의 코드에서 몇 가지 변화를 시도해 보았다.

public class ThrustR extends JFrame { 
 
// public String path; 
 
// public File file; 
 
// public BufferedImage image; 
 

 
// public void setValues() 
 
// { 
 
    // path = "/CityRed.jpg"; 
 
    // file = new File(path); 
 
    //image = ImageIO.read(file); 
 
// } 
 
    public ThrustR(String title) throws IOException { 
 
     super(title); 
 
     String path = "CityRed.jpg"; 
 
     File file = new File(path); 
 
     BufferedImage image = ImageIO.read(file); 
 
     JLabel back = new JLabel(new ImageIcon(image)); 
 
     this.add(back); 
 

 
    } 
 

 
    public static void main(String[] args) throws IOException { 
 
     // Main Window 
 
     ThrustR frame = new ThrustR("ThrustR"); 
 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
 
     frame.setSize(720, 480); 
 
     frame.setVisible(true); 
 

 
    } 
 
}

관련 문제