AlecR
AlecR

Reputation: 57

drawImage() does not draw image

I'm trying to get a .jpg image to draw on the screen using the drawImage() method, but It will not draw. Here is the code:

public void paint(Graphics g) {
        Image image = new ImageIcon("tictactoeimg.jpg").getImage();
        g.drawImage(image, 0, 0, this);
}

The .jpg file is within the src folder with the class. How can I fix this so it will draw the image?

Upvotes: 0

Views: 480

Answers (1)

camickr
camickr

Reputation: 324197

  1. Custom painting is done by overriding the paintComponent() method
  2. Don't do I/O in a painting method. Painting methods are for painting.
  3. Override the getPreferredSize() method of the component to return the size of the component otherwise the size is (0, 0) and there is nothing to paint.

Read the section from the Swing tutorial on Custom Painting for more information.

However, the real question is why are you trying to use drawImage. You can just use a JLabel with an Icon. The tutorial also has a section on How to Use Icons which contains a working example.

Upvotes: 4

Related Questions