Exikle
Exikle

Reputation: 1165

Eclipse, won't import an image?

For some reason the following code is not importing the image correctly and displaying it. If I comment out the draw part it work. I can not figure out why.

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

public class BoardBuild extends JPanel{
    String picPath = "pictures/";
    String[] fileName = {"board.png"};
    ClassLoader cl = BoardBuild.class.getClassLoader();
    URL imgURL[] = new URL[1];
    Toolkit tk = Toolkit.getDefaultToolkit();
    Image imgBG;
    public BoardBuild() throws Exception {
        for (int x = 0; x < 1; x++)
            imgURL[x] = cl.getResource(picPath + fileName[x]);
        imgBG = tk.createImage(imgURL[0]);
    }
    public void paintComponent(Graphics g) {
        g.drawImage(imgBG, 0, 0, 150,150 , 0, 0,73, 73, this);
    }
}

As it is Eclipse, the pictures are in the folder workspace\BoardMaskTest\src\pictures. I would appreciate the help.

Upvotes: 0

Views: 285

Answers (3)

Joop Eggen
Joop Eggen

Reputation: 109547

Resources are taken from from the class path, looking with 7zip or Winzip in the jar one sees:

String picPath = "/pictures/";

Furthermore the image can be loaded as

    for (int x = 0; x < 1; x++)
        URL url = getClass(().getResource(picPath + fileName[x]);
        imgBG = ImageIO.read(url);
        InputStream in = getClass(().getResourceAsStream(picPath + fileName[x]);
        imgBG = ImageIO.read(in);

Upvotes: 1

aly
aly

Reputation: 523

Don't include the "src" in the picPath

 String picPath = "/pictures/";

Upvotes: 1

tckmn
tckmn

Reputation: 59283

Put under here:

workspace/BoardMaskTest/pictures/

Change your path accordingly.

Upvotes: 0

Related Questions