我一直试图用箭头键进行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;
}
}
}
答案 0 :(得分:5)
paint(...)
而是覆盖paintComponent(...)
。paintComponent(...)
。