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。這是我的第一個項目,所以我對我缺乏知識表示歉意。
什麼? 'Graphics g = null;'?? –