Search code examples
javaswingawtkeylistenerpaintcomponent

Image does not move


My image does not move.
Here is the entire code of the application:

package Game;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Game extends JPanel {

    private static final long serialVersionUID = 1L;

    private BufferedImage image;

    public static final int WIDTH = 600;
    public static final int HEIGHT = 500;
    private int x = 1;
    private int y = 1;

    private static int dx;
    private static int dy;

    private boolean leftPressed = false;
    private boolean rightPressed = false;
    private boolean topPressed = false;
    private boolean downPressed = false;

    public static void main(String avg[]) throws IOException {
        Game abc = new Game();

    }

    public Game() {
        try {
            JFrame frame = new JFrame();
            image = ImageIO.read(new File(
                    "C:\\Users\\дНМ\\workspace\\Game\\image\\heroG.png"));

            frame.setSize(WIDTH, HEIGHT);
            frame.setVisible(true);
            frame.getContentPane().add(this);
            this.setBackground(Color.BLACK);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setTitle("Tittle - Game");
            addKeyListener(new KeyInputHandler());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }



    public void move() {

        x += dx;
        y += dy;

        if (x < 1) {
            x = 1;
        }

        if (y < 1) {
            y = 1;
        }
    }

    public void update(long delta) {
        if (leftPressed == true) {
            x--;
        }
        if (rightPressed == true) {
            x++;
        }
    }

    public void update2(long delta) {
        if (downPressed == true) {
            y--;
        }
        if (topPressed == true) {
            y++;
        }
    }

    private class KeyInputHandler extends KeyAdapter {
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                leftPressed = true;
                dx = -1;
            }
            if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                rightPressed = true;
                dx = 1;
            }
            if (e.getKeyCode() == KeyEvent.VK_UP) {
                topPressed = true;
                dy = -1;
            }
            if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                downPressed = true;
                dy = 1;
            }
        }

        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                leftPressed = false;
                dx = 0;
            }
            if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                rightPressed = false;
                dx = 0;
            }
            if (e.getKeyCode() == KeyEvent.VK_UP) {
                topPressed = false;
                dy = 0;
            }
            if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                downPressed = false;
                dy = 0;
            }
        }
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, x, y, null); 
    }
}

What's wrong with it?
Please indicate the errors that you may need to add.


Solution

  • First: Your panel is not intercepting the key events, check other questions like this: addKeyListener() doesn't work for JPanel

    Second: You change the variables dx and dy when a key is pressed, but you are not calling move() method

    Third You are not repainting after each key is pressed.

    These are the modifications:

    Game Constructor

    public Game() {
        try {
            JFrame frame = new JFrame();
            image = ImageIO.read(new File("Zombatar.jpg"));
    
            frame.setSize(WIDTH, HEIGHT);
            frame.setVisible(true);
            frame.getContentPane().add(this);
            this.setBackground(Color.BLACK);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setTitle("Tittle - Game");
    
            addKeyListener(new KeyInputHandler());
    
            //this is important to intercept key events
            setFocusable(true);
            requestFocusInWindow();
    
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    

    KeyAdapter

    private class KeyInputHandler extends KeyAdapter {
    
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                dx = -1;
            }
            else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                dx = 1;
            }
            else if (e.getKeyCode() == KeyEvent.VK_UP) {
                dy = -1;
            }
            else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                dy = 1;
            }
    
            //first call move to update x and y and later repaint tha JPanel
            move();
            repaint();
        }
    }