1

When I tried to to create an image I was using this line but got no images, just blank lines.

g.drawImage(getImage(getDocumentBase(), "Piece_1.png"),coorx, 
coory, SIZE_Y / 8, SIZE_Y / 8, this);

How do you display an image and where do you put it in an eclipse project?

Chris
  • 85
  • 3
  • 12

1 Answers1

1

Eclipse IDE executes the programs from the src directory. These steps solved me this problem.

  1. Create a new package called resources. You can name it whatever you want.
  2. Add your image files into that package.
  3. Now first load your image before drawing it.

    public Image getImage(String name){
        URL imgUrl = getClass().getClassLoader().getResource("resources/"+name);
        ImageIcon icon = new ImageIcon(imgUrl);
        return icon.getImage();
    }
    

An Example

The constructor you can have.

Image piece1;

public Checkers(){
    piece1 = getImage("Piece_1.png");
}

public void paint(Graphics g){
    if (piece1!=null){
        g.drawImage(piece1, xcoord, ycoord, null);
    }
}

Hope this solves your problem.

Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91