0

I am trying to make a JButton that displays an image in the JPanel when pressed - allowing the user to choose the location in the panel. I am using the following methods to paint:

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;
}

When I call paint(), I get a null pointer exception in my last line of my 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"));
        }

I'm a little confused overall about how to use ActionListeners. This is my first project so I apologize for my lack of knowledge.

meghan152
  • 11
  • 2

1 Answers1

1

You have set Graphics g = null;

Initialize g with something other than null.

I would recommend overriding public void paintComponent(Graphics g) of the JPanel where you plan to paint and use this graphics.

Soma
  • 24
  • 4