My problem is that the image is not showing on my java.

here is my code

MyGame.java

package mygame;

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

public class MyGame extends JFrame {
    Container c;
    Player p;
    MyGame()
    {
        this.setTitle("My Game");
        this.setSize(600, 400);
        this.setLocation(100, 100);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        c = this.getContentPane();
	p = new Player();
	c.add(p);
	this.addKeyListener(p);
    }
    
    public static void main(String[] args) {
        MyGame m = new MyGame();
        m.setVisible(true);
    }
}

Player.java

package mygame;

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

public class Player extends JPanel implements KeyListener {
    int x=10,y=10, ctr=1;
    ImageIcon img = new ImageIcon("image.gif");
    
    public void paint (Graphics g)
    {
        super.paint(g);
        g.setColor(Color.GRAY);
        g.fillRect(0,0,600,400);
        g.drawImage(img.getImage(), x, y, null);
        
    }
    
    public void keyPressed(KeyEvent e){
        int i = e.getKeyCode();
        String key = KeyEvent.getKeyText(i);
        
        if (key.equals("Up"))
        {
            y=y-3;
            ctr=ctr%6+1;
            img = new ImageIcon("d"+ctr+".gif");
            this.repaint();
        }
    }
    
    public void keyReleased(KeyEvent e){}
    public void keyTyped(KeyEvent e){}
}

Recommended Answers

All 7 Replies

I think you need to set the layout first.

what do you mean? can u tell me how?

Are you sure the image file is being found?
The code works for me.

BTW use the paintComponent method in Swing components vs paint

commented: great catch +9

and use KeyBindings instead of KeyListener

you have to setFocus() for JPanel, otherwise pretty to ignore any output from keyboard

i put the image inside the src folder with my .java files. but still not working

You can Keep copying the image to different folders until you find where the program is looking for it,
or Try creating a File object with the path to the image file you are using and print out the absolutePath of that file object to see where the JVM is looking for the file.

thnx. now it works. i put all the images outside the src folder and it works.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.