使用KeyListener在JPanel中使用箭头键移动矩形

使用KeyListener在JPanel中使用箭头键移动矩形

问题描述:

我一直在尝试使用箭头键移动JPanel.它没有工作.我相信是扩展KeyAdapter的内部类.我也不确定是否实现了ActionListener.我参加的其他课程并不重要,因为它只是框架.

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;
    }
}

}

  • 您将要在本网站上搜索类似的问题,因为它们通常具有相同的问题和相同的答案.
  • 他们会告诉您焦点是一个问题,因为组件的KeyListener除非有焦点,否则将无法工作.
  • 他们会告诉您,无论您什么时候都不要使用KeyListener,而应该只使用Key Bindings.
  • 除非您确定要覆盖组件的边框和子对象的绘画(不要),否则它们会告诉您不要覆盖paint(...)而是覆盖paintComponent(...).
  • 他们会告诉您确保在paintComponent(...)内部调用super方法.
    • 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(...).
    • 还请查看此动画和键绑定示例.