Igor Meszaros
Igor Meszaros

Reputation: 2127

Image drawing with PaintComponent Java

I'm studying java currently, and yet again I ran into a code in the book which doesn't wanna work and i can't figure out why. This code snippet is from Head First Java

import javax.swing.*;
import java.awt.*;

public class SimpleGui {

    public static void main (String[] args){
        JFrame frame = new JFrame();
        DrawPanel button = new DrawPanel();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.getContentPane().add(button);

        frame.setSize(300,300);

        frame.setVisible(true);
    }
}


import java.awt.*;
import java.lang.*;

public class DrawPanel extends JPanel {
private Image image;

public DrawPanel(){
    image = new ImageIcon("cat2.jpg").getImage();
}
public void paintComponent(Graphics g){

    g.drawImage(image,3,4,this);
    }
}

the image is in the same directory where my class files are, and the image is not showing. What am i missing here?

Upvotes: 1

Views: 15156

Answers (1)

alex2410
alex2410

Reputation: 10994

1) In your paintComponent() you must to call super.paintComponent(g);. Read more about custom paintings.

2) instead of Image use BufferedImage, because Image its abstrat wrapper.

3)use ImageIO instead of creating Image like this new ImageIcon("cat2.jpg").getImage();

4)Use URL for resources inside your project.

I changed your code and it helps you:

class DrawPanel extends JPanel {
    private BufferedImage image;

    public DrawPanel() {
        URL resource = getClass().getResource("cat2.jpg");
        try {
            image = ImageIO.read(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 3, 4, this);
    }
}

Upvotes: 2

Related Questions