Moving a rectangle in JPanel with arrow keys using KeyListener

半城伤御伤魂 提交于 2020-01-06 08:12:58

问题


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.



来源:https://stackoverflow.com/questions/17246443/moving-a-rectangle-in-jpanel-with-arrow-keys-using-keylistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!