【问题标题】:Java keylistener use arrow keys to move carJava keylistener 使用箭头键移动汽车
【发布时间】:2013-02-27 16:33:29
【问题描述】:

我正在尝试实现一个按键监听器,以使用箭头键在我的程序中移动汽车。 这是我的代码。

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

我相信这就是您需要的所有代码,但如果您需要我的其他代码,我可以得到。 谢谢

【问题讨论】:

  • 嗯...你的问题是什么?
  • 请告诉我们您的问题
  • KeyListener 到底是在哪里声明的?无论如何,Swing 使用KeyBindings 而不是KeyListener。见this similar answer

标签: java swing keylistener


【解决方案1】:

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

【讨论】:

  • 我不知道如何实现键绑定
【解决方案2】:

你必须使用 addKeyListener:

addKeyListener(yourKeyListener);

看到这个minimal example

【讨论】:

    猜你喜欢
    • 2013-06-19
    • 2012-02-16
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多