简体   繁体   中英

adding images to a java applet?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM