简体   繁体   中英

Java keylistener use arrow keys to move car

I am trying to implement a keylistener to move the car in my program using the arrow keys. Here is my code.

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);
}
}

I believe that is all the code you will need, but if you need my other code I can get that. Thank you

You haven't added any key bindings to your application. Check out the Java tutorial on swing key bindings for information on how to do this.

You have to use addKeyListener:

addKeyListener(yourKeyListener);

See this minimal example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM