2013-02-27 71 views
0

我想實現一個keylistener在我的程序中使用箭頭鍵移動汽車。 這是我的代碼。Java的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); 
} 
} 

我相信這是你需要的所有代碼,但是如果你需要我的其他代碼,我可以得到它。 謝謝

+2

那麼...你的問題是什麼? – 2013-02-27 16:35:47

+0

請告訴我們您的問題 – 2013-02-27 16:37:03

+1

在哪裏聲明瞭KeyListener?無論如何,Swing使用['KeyBinding's](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html)而不是'KeyListener'。請參閱[這個相似的答案](http://stackoverflow.com/questions/13770185/why-isnt-the-keylistener-working/13770483#13770483) – 2013-02-27 16:48:01

回答

-1

你必須使用addKeyListener:

addKeyListener(yourKeyListener); 

看到這個minimal example

0

您尚未將任何鍵綁定添加到您的應用程序。有關如何執行此操作的信息,請查看swing key bindings上的Java教程。

+0

我不知道如何實現鍵盤綁定 – user2116211 2013-03-13 02:53:51

+0

然後閱讀教程是最好的地方開始。 – vainolo 2013-03-13 19:35:58