0

Here's a simple question: how to get the source of an image. The following are the codes of subclass:

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

public class PuzzleGameBoard extends JComponent {

private Image penguin;

public PuzzleGameBoard() {

    penguin = ;
}

public void paintComponent(Graphics g) {
    g.setColor(Color.BLACK);
    g.fillRect(0,  0, getWidth(), getHeight());

    g.drawImage(penguin,  30, 30, this);
}

}

I have problem printscreening my java program and my files to be uploaded due to technique limitation. But can anybody teach me the best way of getting the source of an image? Sorry to be not quite specific again..

tommy
  • 11
  • 2

1 Answers1

0

It's worth reading Java Tutorial on Loading Images Using getResource


Just put all the images inside the project itself or bundle all the required resources in a jar and add it in the class-path, then try any one based on image location.

// Read from same package 
ImageIO.read(getClass().getResourceAsStream("c.png"));

// Read from images folder parallel to src in your project
ImageIO.read(new File("images/c.jpg"));

// Read from src/images folder
ImageIO.read(getClass().getResource("/images/c.png"))

// Read from src/images folder
ImageIO.read(getClass().getResourceAsStream("/images/c.png"))

Read more...

Note: Call super.paintComponent(g); at first line in the overridden paintComponent() method.

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76