我一直在尝试JPanel
用箭头键移动。它一直没有工作。我相信是我的内部类扩展了KeyAdapter
. 我也不确定是否已ActionListener
实施。我做的另一个类无关紧要,因为它只是框架。
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;
}
}
}