Moving a rectangle in JPanel with arrow keys using

2019-08-30 02:46发布

问题:

I have been trying to make a JPanel move with the arrow keys. It has not been working. I believe it is my inner class that extends the KeyAdapter. I'm also not sure about the ActionListener implemented were it is. The other class I have made does not matter since it is just the frame.

package jerryWorlds;

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

public class Jerry extends JPanel implements ActionListener{

int SizeX, SizeY, PosX, PosY, VelX, VelY;
Image img;
Timer time = new Timer(1, this);

public Jerry(){
    ImageIcon i = new ImageIcon();
    addKeyListener(new AL());
    time.start();
    img = i.getImage();
    PosX = 375;
    PosY = 250;
}

public void paint(Graphics g){
    Graphics2D g2d = (Graphics2D)g;
    g2d.fillRect(PosX, PosY, 50, 100);
}
public void actionPerformed(ActionEvent e) {
    PosX = PosX + VelX;
    repaint();
}

private class AL extends KeyAdapter{
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        System.out.println("YAY!");
        if(key == KeyEvent.VK_LEFT)
            VelX = -1;
        else if(key == KeyEvent.VK_RIGHT)
            VelX = 1;
    }

    public void keyReleased(KeyEvent e) {
        int key = e.getKeyCode();
        if(key == KeyEvent.VK_LEFT)
            VelX = 0;
        else if(key == KeyEvent.VK_RIGHT)
            VelX = 0;
    }
}

}

回答1:

  • You will want to search this site for similar questions, as they usually have the same issue and same answer.
  • They will tell you that focus is one problem since a component's KeyListener won't work unless it has focus.
  • They will tell you that regardless you shouldn't use KeyListener at all but rather Key Bindings.
  • They will tell you not to override paint(...) but rather paintComponent(...) unless you are sure that you want to override painting of a component's borders and children (you don't).
  • They will tell you to be sure to call the super method inside of paintComponent(...).

Also please have a look at this animation and key bindings example.