2012-08-03 65 views
2

我的問題是,當我點擊框架屏幕的空間時,它停止鍵盤按鍵被註冊,所以我的播放器停止移動。JFrame鼠標單擊停止鍵盤按鈕

在此先感謝您的幫助。

代碼:

private Component comp; 
.... 

public InputManager(Component comp) { 
    this.comp = comp; 
    mouseLocation = new Point(); 
    centerLocation = new Point(); 

    // register key and mouse listeners 
    comp.addKeyListener(this); 
    comp.addMouseListener(this); 
    comp.addMouseMotionListener(this); 
    comp.addMouseWheelListener(this); 

    // allow input of the TAB key and other keys normally 
    // used for focus traversal 
    comp.setFocusTraversalKeysEnabled(false); 
} 

GUI代碼:

Game game = new Game(); 
    game.setMinimumSize(new Dimension(WIDTH * 2, HEIGHT * 2)); 
    game.setPreferredSize(new Dimension(WIDTH * 2, HEIGHT * 2)); 
    game.setMaximumSize(new Dimension(WIDTH * 2, HEIGHT * 2)); 

    frame = new JFrame(Game.NAME); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setLayout(new BorderLayout()); 
    frame.add(game); 
    frame.pack(); 
    frame.setResizable(false); 
    frame.setLocationRelativeTo(null); 
    frame.setVisible(true); 
    game.start(); 

回答

9

我假設你正在使用的KeyListener監聽按鍵輸入。請注意,這隻有在被監聽的組件具有焦點時纔有效,並且可能在JFrame上按下鼠標時,聽衆組件失去焦點。

解決方案不是使用KeyListener,而是使用Key Bindings,它比KeyListener和更高級別的概念更健壯。

此外,您將要停止使用作爲您的聽衆。如果你的程序不僅僅是一個玩具程序,它還很難維護一個GUI類,它將自己用作自己的聽衆。

此外,關於:「哦是的Game.java擴展Canvas」:你不想混淆AWT和Swing組件不必要的,因爲這可能會導致副作用。相反,只需使用所有的Swing組件,如JPanels而不是Canvases。

+2

+1鍵綁定。停止使用+1作爲偵聽器,使用+1作爲混音備註。嗯,我需要upvote兩個其他職位給你你的信用? – Robin 2012-08-03 22:07:18

+0

謝謝,這幫助了很多。我一定會嘗試關鍵綁定。 – DCSoft 2012-08-03 22:34:25

+0

我找到了一個臨時解決方案,我已經將遊戲類傳入InputManager類而不是JFrame。 – DCSoft 2012-08-03 22:50:13

相關問題