[英]How to use KeyListener for moving Rectangles
I am trying to move a rectangle while the key is pressed and to stop it on release like the game "Snake".我试图在按下键时移动一个矩形,并像游戏“Snake”一样在释放时停止它。 As reference I followed this tutorial.
作为参考,我遵循了本教程。
I tried to adjust a few things in my code:我试图在我的代码中调整一些东西:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
public class f3 extends JPanel implements ActionListener, KeyListener {
static JFrame frame;
static Timer t;
static int x, y, velx, vely, c;
f3(){
t = new Timer(5, this);
x = 0;
y = 0;
velx = 0;
vely = 0;
frame = new JFrame();
frame.addKeyListener(this);
frame.setFocusable(true);
frame.setFocusTraversalKeysEnabled(false);
frame.setSize(500,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.setVisible(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(x, y, 50, 30);
t.start();
}
public void actionPerformed(ActionEvent e) {
x = x + velx;
y = y + vely;
repaint();
}
public void keyPressed(KeyEvent e) {
c = e.getKeyCode();
if(c == KeyEvent.VK_RIGHT) {
velx = 1;
vely = 0;
}
if(c == KeyEvent.VK_LEFT) {
velx = -1;
vely = 0;
}
if(c == KeyEvent.VK_UP) {
velx = 0;
vely = -1;
}
if(c == KeyEvent.VK_DOWN) {
velx = 0;
vely = 1;
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public static void main(String args[]) {
new f3();
}
}
The value of velx
and vely
are set after a key event is triggered. velx
和vely
的值是在触发按键事件后设置的。 Since you are using a Timer
here, the GUI will continuously update because actionPerformed
is repeatedly triggered.由于您在这里使用
Timer
,GUI 将不断更新,因为actionPerformed
被重复触发。
Remove the Timer
, then put the change section of keyPressed
to this form and you will get a desired result.删除
Timer
,然后将keyPressed
的更改部分放入此表单,您将获得所需的结果。
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
velx = 1;
vely = 0;
x = x + velx;
y = y + vely;
repaint();
}
}
由于velx
和vely
指示移动的速度(例如,与玩家一次移动一个空间相反),您还需要确保当与该轴关联的特定键被释放时, keyReleased
将适当的速度返回到 0 .
You do not have a handler for keyReleased method, where you should set velocities to zero as such:您没有 keyReleased 方法的处理程序,您应该将速度设置为零,如下所示:
public void keyReleased(KeyEvent e) {
velx = 0;
vely = 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.