我即将完成我正在进行的这个汽车项目,但似乎无法让关键事件发挥作用。我认为这与我的 Action 监听器和计时器有关,但我不确定。当我按向上箭头键时,计时器延迟应该减少,反之亦然。我已编写命令,但它们没有注册输入。如果有人能给我一些指示,我将不胜感激
代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RaceCar extends JFrame{
public RaceCar(){
add(new CarPic());
}
public static void main(String[] args){
JFrame frame = new RaceCar();
frame.setTitle("Brady Kedge: Race Car");
frame.setSize(300, 150);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public class CarPic extends JPanel implements KeyListener
{
private int x = 0;
private int y = 150;
private int z = 300;
Timer mytimer = new Timer(50, new ActionListener());
public CarPic()
{
mytimer.start();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
y = getHeight();
z = getWidth();
g.setColor(Color.WHITE);
g.fillRect(0, 0, z, y);
Polygon polygon = new Polygon();
polygon.addPoint(x + 10, y - 20);
polygon.addPoint(x + 20, y - 30);
polygon.addPoint(x + 30, y - 30);
polygon.addPoint(x + 40, y - 20);
if(x < z - 40)
{
g.setColor(Color.BLACK);
g.fillOval(x + 10, y - 10, 10, 10);
g.fillOval(x + 30, y - 10, 10, 10);
g.setColor(Color.BLUE);
g.fillRect(x, y - 20, 50, 10);
g.setColor(Color.BLUE);
g.fillPolygon(polygon);
}
else
x = 0;
}
public void actionPerformed(ActionEvent e){
x+=10;
repaint();
}
@Override
public void keyTyped(KeyEvent k) {
//Fill
}
@Override
public void keyPressed(KeyEvent k) {
int delay = mytimer.getDelay();
if(k.getKeyCode() == KeyEvent.VK_UP)
mytimer.setDelay(delay > 10 ? delay - 10 : 0);
else if(k.getKeyCode() == KeyEvent.VK_DOWN)
mytimer.setDelay(delay < 5000 ? delay + 10 : 5000);
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
}
最佳答案
首先,您永远不会向组件注册 KeyListener
(实现 KeyListener
是不够的)。
其次,KeyListener
仅在注册的组件具有焦点且可聚焦时才会引发 KeyEvents
。
更好的解决方案是使用 key bindings API ,它为您提供了配置组件触发关键事件的焦点级别的方法。
另外,就个人而言,我不会修改Timer
延迟,而是使用速度修改器(double
类型),它是您想要的速度的百分比。例如,1
为正常速度,0.5
为半速,2
为双速。
关于Java按键事件和定时器控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23553711/