Java keylistener使用箭头键移动汽车

Java keylistener使用箭头键移动汽车,java,swing,keylistener,Java,Swing,Keylistener,我试图实现一个keylistener,在我的程序中使用箭头键移动汽车。 这是我的密码 package moveCar; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CPanel extends JPanel{ private static final long serialVersionUID = 1L; CarComponent component; public CPanel

我试图实现一个keylistener,在我的程序中使用箭头键移动汽车。 这是我的密码

package moveCar;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CPanel extends JPanel{ 
private static final long serialVersionUID = 1L;
CarComponent component;
public CPanel() {
    component = new CarComponent();
    JButton startButton = new JButton("Start");
    JButton stopButton = new JButton("Stop");
    startButton.addActionListener(new StartAction());
    stopButton.addActionListener(new StopAction());

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new FlowLayout());
    buttonPanel.add(startButton);
    buttonPanel.add(stopButton);

    this.setLayout(new BorderLayout());
    this.add(buttonPanel, BorderLayout.NORTH);
    this.add(component, BorderLayout.SOUTH);
}

class StartAction implements ActionListener {
    public void actionPerformed(ActionEvent e){
        component.setAnimation(true);
    }
}
class StopAction implements ActionListener {
    public void actionPerformed(ActionEvent e){
        component.setAnimation(false);
    }
}
}

package moveCar;

import javax.swing.*;

public class CarViewer  {
CPanel a = new CPanel();
public CarViewer(){
    a.add(new CPanel());
}
public static void main(String[] arg){
    JFrame frame = new JFrame();
    //frame.setSize(800,200);
    frame.setTitle("This is strange .....");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new CPanel());
    frame.pack();
    frame.setVisible(true);
}
}
我相信这就是你需要的全部代码,但是如果你需要我的其他代码,我可以得到。
谢谢

您必须使用addKeyListener:

addKeyListener(yourKeyListener);

请参阅此图。

您尚未向应用程序添加任何密钥绑定。查看上的Java教程,了解如何执行此操作。

好吧。。。你的问题是什么?请告诉我们你的问题
KeyListener
到底在哪里声明的?无论如何,Swing使用而不是
键侦听器
。看,我不知道如何实现键绑定