简体   繁体   中英

How to move image in Applet using KeyListener?

I'm trying to make an Applet that displays two images and allows the user to move one of them using the left/ right arrow keys (or keys a and d). On the bright side, I know I imported the images correctly because it displays both of them once I run the the program; however, once I press the left or right key an error promptly pops up and the image doesn't move as I intended. If someone could tell me what's wrong and explain the details on what I need to fix that would be a great help. Thanks in advance.

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class mainClass extends Applet implements KeyListener {
Image pic1, pic2;
int x=0, y=0,move=5;

public void init(){
    setSize (1600,1200);
    pic1 = getImage(getDocumentBase(),"beach king.jpg");
    pic2 = getImage(getDocumentBase(),"eye.jpg"); 
    addKeyListener(this);
}
public void start(){

}
public void paint(Graphics g){
    //setBackground(Color.CYAN);
    try{Thread.sleep(100);} 
    catch(Exception e){}
    //going to change position of pic1
    g.drawImage(pic1, x, y, this);
    g.drawImage(pic2, 0, 0, this);
}

private boolean[] keys;

public void keyPressed(KeyEvent e) {
    keys[e.getKeyCode()] = true;
}

public void keyReleased(KeyEvent e) {
    keys[e.getKeyCode()] = false;
}
public void keyTyped(KeyEvent e) {}

public void update() {
    if(keys[KeyEvent.VK_A] || keys[KeyEvent.VK_LEFT]){
       x-=move;
    }
    if(keys[KeyEvent.VK_D] || keys[KeyEvent.VK_RIGHT]){
       x+=move;
    }
}

}

One issue with your code is that you never initialize the array private boolean[] keys , but since you are just trying to change the x-position of your image, it is highly impractical to use a boolean array. Instead, just update the x value whenever a key is pressed.

Your keyPressed function looks then as follows:

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_LEFT) {
        x-=move;
    }
    else if (e.getKeyCode() == KeyEvent.VK_D || e.getKeyCode() == KeyEvent.VK_RIGHT) {
        x+=move;
    }
    this.repaint();
}

In the last line of this method you call repaint, such that the applet actually redraws the image.

You can then leave the keyReleased method empty, because you don't need to reset any value. Finally, delete your update method, as it is never called (the other methods in your code are called because they are either specified in the super class or in the interface).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM