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

here is my code

package mygame;

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

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

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)
        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"))
            img = new ImageIcon("d"+ctr+".gif");
    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, learning, and sharing knowledge.