簡體   English   中英

Java Keylistener使用箭頭鍵移動汽車

[英]Java keylistener use arrow keys to move car

我正在嘗試實現按鍵偵聽器,以使用箭頭鍵在程序中移動汽車。 這是我的代碼。

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

我相信這就是您所需要的全部代碼,但是如果您需要我的其他代碼,我可以得到。 謝謝

您尚未向應用程序添加任何鍵綁定。 查看有關揮桿鍵綁定的Java教程,以獲取有關如何執行此操作的信息。

您必須使用addKeyListener:

addKeyListener(yourKeyListener);

請參閱此最小示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM