0

I want to make object(police) moves for my keys(W,A,S,D).

when i run these codes on eclipse, there are no errors and it work well except about moving. Despite i pressed keys(W,A,S,D), object(police) doesn't have reaction.

As i think, it seems have problem on KeyListener in public ChaseThief

Help me please. Thank you.

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.ImageIcon;
import javax.swing.JFrame;

public class ChaseThief extends JFrame {
    private Image bufferImage;
    private Graphics screenGraphic;
    
    private Image background = new ImageIcon("src/images/background.jpg").getImage();
    private Image police = new ImageIcon("src/images/police.jpg").getImage();
    private Image thief = new ImageIcon("src/images/thief.png").getImage();
    
    private int policeX, policeY;
    private int policeWidth = police.getWidth(null);
    private int policeHeight = police.getWidth(null);
    private int thiefX, thiefY;
    private int thiefWidth = thief.getWidth(null);
    private int thiefHeight = thief.getWidth(null);
    
    private int score;
    
    private boolean up, down, left, right;
    private KeyListener listener;
    
    
    public ChaseThief() {
        setTitle("Game : 도둑잡기");
        
        setSize(800,600);
        setResizable(false);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        start();
        setVisible(true);
        listener = new KeyListener() {

            @Override
            public void keyPressed(KeyEvent e) {
                switch(e.getKeyCode()) {
                case KeyEvent.VK_W:
                    up=true;
                    break;
                case KeyEvent.VK_S:
                    down=true;
                    break;
                case KeyEvent.VK_A:
                    left=true;
                    break;
                case KeyEvent.VK_D:
                    right=true;
                    break;
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
                switch(e.getKeyCode()) {
                case KeyEvent.VK_W:
                    up=false;
                    break;
                case KeyEvent.VK_S:
                    down=false;
                    break;
                case KeyEvent.VK_A:
                    left=false;
                    break;
                case KeyEvent.VK_D:
                    right=false;
                    break;
                }
            }

            @Override
            public void keyTyped(KeyEvent e) {
            }
        };
        while(true) {
            catchThief();
        }
    }

    public void start() {
        score = 0;
        policeX = (800-policeWidth)/2;
        policeY = (600-policeHeight)/2;
        thiefX=(int)(Math.random()*800);
        thiefY=(int)(Math.random()*600);
    }
    
    public void MovePolice() {
        if (up && policeY - 3 > 50) policeY -=3;
        if (down && policeY + policeHeight + 3 < 600) policeY+=3;
        if (left && policeX - 3 > 0) policeX-=3;
        if(right && policeX+policeWidth +3 < 800) policeX+=3;
        
    }
    
    public void catchThief() {
        if(policeX + policeWidth > thiefX && thiefX + thiefWidth > policeX && policeY + policeHeight > thiefY && thiefY + thiefHeight > policeY ) {
            score += 1;
            thiefX=(int)(Math.random()*800);
            thiefY=(int)(Math.random()*600);
        }
    }
    
    
    public void paint(Graphics g) {
        bufferImage = createImage(800,600);
        screenGraphic = bufferImage.getGraphics();
        draw(screenGraphic);
        g.drawImage(bufferImage, 0, 0, null);
    }
    
    public void draw(Graphics g) {
        g.drawImage(background,0,0,null);
        g.drawImage(police,policeX,policeY,null);
        g.drawImage(thief,thiefX,thiefY,null);
        g.setColor(Color.BLACK);
        g.setFont(new Font("Arial", Font.BOLD, 40));
        g.drawString("SCORE : "+score, 50, 80);
        this.repaint();
    }
    public static void main(String[] args) {
        new ChaseThief();
    }
}

  • 2
    1) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). E.G. The code in [this answer](https://stackoverflow.com/a/10862262/418556) hot links to an image embedded in [this question](https://stackoverflow.com/q/10861852/418556). 2) For Swing, we typically use [key bindings](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) rather than the lower level `KeyListener`. 3) Don't block the EDT (Event Dispatch Thread). The GUI will 'freeze' when that happens. .. – Andrew Thompson Dec 19 '20 at 21:26
  • 1
    .. See [Concurrency in Swing](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for details and the fix. – Andrew Thompson Dec 19 '20 at 21:26
  • Thank you andrew. your answer was very helpful to me. – Kim ByeongHwa Dec 19 '20 at 21:46
  • 1
    You're welcome. :) Let us know if you solve it. (Note that it was a comment though, not an answer.) – Andrew Thompson Dec 19 '20 at 23:22
  • 2
    1) Don't override paint() on a JFrame 2) Custom painting is done by overriding the paintComponent() method of a JPanel (or JComponent) and then you add the panel to the frame. 3) There is no need to create a BufferedImage in your painting method. Swing is double buffered by default, so you just do your custom painting with the Graphics object passed to the paintComponent() method. 4) Don't invoke repaint() in a painting method. 5) Don't use a while loop for your game logic. If you need animation use a `Swing Timer` (which replaces the looping logic. – camickr Dec 20 '20 at 00:27
  • 2
    6) you create a KeyLIstener, but you never add the listener to any component. In any case you should NOT be using a KeyListener. Instead you should be using Key Bindings (as has already been mentioned) 7) See [Motion Using the Keyboard](https://tips4java.wordpress.com/2013/06/09/motion-using-the-keyboard/) for working examples showing the difference between a KeyListener and Key Bindings. 8) method names should NOT start with an upper case character. – camickr Dec 20 '20 at 00:29
  • 1
    Adding to everyone's comment I've been working on a Swibg game library which demonstrates much of what is needed to create a game in swing, here is an [example class for a KeyBinding](https://github.com/davidkroukamp/SwingGameLibrary/blob/main/src/za/co/swinggamelibrary/KeyBinder.java) and an [example usage class](https://github.com/davidkroukamp/SwingGameLibrary-Samples/blob/main/sample1/src/sgltest/SGLTest.java) search for the `setupPlayer1KeyBindings` method. – David Kroukamp Dec 20 '20 at 07:50
  • 1
    Take a look at my [2048 game](https://github.com/ggleblanc2/2048/blob/main/src/com/ggl/game2048/view/Game2048Frame.java) for a working example of Key Bindings. – Gilbert Le Blanc Dec 20 '20 at 11:00

0 Answers0