使用KeyListener在JPanel中使用箭头键移动矩形 [英] Moving a rectangle in JPanel with arrow keys using KeyListener

查看:164
本文介绍了使用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(...).
    • 还请查看此动画和键绑定示例.

      这篇关于使用KeyListener在JPanel中使用箭头键移动矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆