2016-11-21 52 views
0

我正在嘗試在按下時在JPanel中顯示圖像的JButton - 允許用戶在面板中選擇位置。我使用下面的方法來作畫:在ActionListener中添加圖像

public void paint(Graphics g, URL path) { 
    Image img = getImage(path); 
    Graphics2D g2 = (Graphics2D)g; 
    g2.drawImage(img, getX(),getY(),50,50, null); 
} 

public Image getImage(URL path) { 
    Image temp = null; 
    try 
    { 
     temp = Toolkit.getDefaultToolkit().getImage(path); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return temp; 
} 

當我調用paint(),我得到了我的我的ActionListener的最後一行空指針異常:

dogButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent ae) { 
      Graphics g = null; 
      Animal animal = new Animal(); 
      animal.paint(g, main.class.getResource("/Animals/dog.jpg")); 
     } 

我有點困惑整體關於如何使用ActionListeners。這是我的第一個項目,所以我對我缺乏知識表示歉意。

+0

什麼? 'Graphics g = null;'?? –

回答

1

您已設置 Graphics g = null;

後來在paint方法你想投它 Graphics2D g2 = (Graphics2D)g;

你不能施放空,因此NPE。

用空格以外的值初始化g。

我建議覆蓋您計劃繪製和使用此圖形的JPanel的public void paintComponent(Graphics g)