2012-03-22 39 views
2

我有一個Game Window到我試圖把W¯¯一個小號d爲滾動鍵爲JScrollPane。這是我迄今在運行它的方法上所做的。 JScrollPane不在本地。當我運行它時,程序運行良好,但鍵不做任何事情。我嘗試了在動作中放置一個斷點,以便它在響應按鈕按下時運行,但它沒有做任何事情。 我將不勝感激任何輸入,讓我知道如果你需要更多的信息。小遊戲在主界面設置W,A,S,d在JScrollPane的

/** 
* This sets all the key commands to the scroll pane for up, down, left, right. 
* These are W, S, A, D 
* It also sets the increment amount. 
*/ 
private void setupScrollKeys() 
{ 
    //sets up the scroll panes unit increment. 
    final int increment = 80; 
    scrollPane.getHorizontalScrollBar().setUnitIncrement(increment); 
    scrollPane.getVerticalScrollBar().setUnitIncrement(increment); 

    //set all the keyStrokes for up, down, left, right on the scroll pane. 
    KeyStroke kUp = KeyStroke.getKeyStroke(KeyEvent.VK_W, 0); 
    KeyStroke kDown = KeyStroke.getKeyStroke(KeyEvent.VK_S, 0); 
    KeyStroke kLeft = KeyStroke.getKeyStroke(KeyEvent.VK_A, 0); 
    KeyStroke kRight = KeyStroke.getKeyStroke(KeyEvent.VK_D, 0); 

    // set W for key up. 
    scrollPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) 
                 .put(kUp, "keyUp"); 
    scrollPane.getActionMap().put("keyUp", new AbstractAction() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      final JScrollBar bar = scrollPane.getVerticalScrollBar(); 
      int currentValue = bar.getValue(); 
      bar.setValue(currentValue - increment); 
     } 
    }); 
} 
+0

+1,使用按鍵綁定,希望我能幫助您在這一點,但我的知識是關於這一主題太少:-) – 2012-03-22 17:04:27

+0

WORKSFORME(也應該爲你以及:-)至少如果)某事scrollPane(或窗格)內部是focusOwner,並且b)沒有其他消耗密鑰。 – kleopatra 2012-03-23 09:52:47

回答

1

嘗試改變線

scrollPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) 
                .put(kUp, "keyUp"); 

scrollPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) 
                 .put(kUp, "keyUp"); 

我沒有鍵綁定的想法,所以我發現這個教程非常方便。 How to Use Key Bindings

+0

全局綁定可以完成,但可能不打算:-) – kleopatra 2012-03-23 09:54:28

+0

真棒,完全解決它。謝謝,我閱讀了幫助頁面,這非常有幫助。再次感謝。 – 2012-03-24 03:46:26