0

previously I haven't been specific enough in my questions, so i'll try to to as best as I can. I'm really new at java, so forgive me if I don't understand basic concepts.

I've been following a tutorial about making a basic java game from Zetcode, and i'm stuck on the movingsprites section. I'm pretty sure my code is correct, but I can't get the "sprite.png" image to appear when I run the program. All I get is a completely black window. I've searched around, and apparently other people had the same problem, but have been unable to resolve it. Perhaps some of you could lead me in the right direction? Here is my code:

public class Craft {

private int dx;
private int dy;
private int x;
private int y;
private Image image;

public Craft() {

    initCraft();
}

private void initCraft() {

    ImageIcon ii = new
    ImageIcon("craft.png");
    image = ii.getImage();
    x = 40;
    y = 60;
}

I placed the file "craft.png" in /zetcode/src/image. I also tried leaving the image in /zetcode, but the same thing still happened.

Thank you in advance!

Bradley Pearl
  • 23
  • 1
  • 6

2 Answers2

0

Follwing the Documentation of how to use ImageIcon try:

java.net.URL imgUrl = Craft.class.getResource("craft.png");
if (imgURL != null) {
    System.out.println("Path Founded Correctly"); 
    ImageIcon icon = new ImageIcon(imgUrl);
} else {
    System.out.println("There isn't an image in the path:" + imgUrl.getPath());
}

if this Code doesn't work try this

java.net.URL imgUrl = getClass().getResource("craft.png");
if (imgURL != null) {
    System.out.println("Path Founded Correctly"); 
    ImageIcon icon = new ImageIcon(imgUrl);
} else {
    System.out.println("There isn't an image in the path:" + imgUrl.getPath());
}
Gatusko
  • 2,503
  • 1
  • 17
  • 25
  • Still no luck, having the same problem. – Bradley Pearl Dec 21 '16 at 16:00
  • Well first we see if there is an image in the path. Try anyone of the code Edited and see where you need to save the image. – Gatusko Dec 21 '16 at 16:08
  • Right, I did that, the output says "There isn't an image in the path:", even though the file is there. – Bradley Pearl Dec 21 '16 at 17:45
  • Okey now i get it what is your problem check this [answer](http://stackoverflow.com/questions/27934796/how-do-i-add-a-resources-folder-to-my-java-project-in-eclipse) you are not adding to the resource folder and added there – Gatusko Dec 21 '16 at 18:19
0

For these kind of questions, which I repeteadly see, I have created the following Displaying an image in Java tutorial.

Jan Bodnar
  • 10,969
  • 6
  • 68
  • 77