2009-06-09 55 views
0

您好我正在使用擺動和在我的主框架(JFrame)我想,當用戶按+鍵一個窗口可以說測試應該出現。 如果我不調用新添加的JInternalFrame的show方法,但是當我調用JInternalFrame的Show方法時,KeyListener將停止監聽,所以我的監聽器可以正常工作。問題keylistener

我已經嘗試了很多來解決它,但都是徒勞,所以任何有關這方面的幫助將不勝感激。 謝謝。

這是我的KeyListener

_mainFrameKeyListener = new KeyListener() 
    { 
     public void keyPressed(KeyEvent arg0) { 
      // TODO Auto-generated method stub 
      System.out.println("the key pressed Id is : " + arg0.getKeyCode()); 

      if(arg0.getKeyCode() == 107){ 
       test Test = new test(); 
       _mainDesktopPane.add(Test); 
       Test.show(); 

      } 
     } 
     public void keyReleased(KeyEvent arg0) { 
      // TODO Auto-generated method stub 
     } 

     public void keyTyped(KeyEvent arg0) { 
      // TODO Auto-generated method stub 
     }   
}; 
+5

test Test = new test(); - 讓我畏縮:) – willcodejavaforfood 2009-06-09 10:06:58

+3

http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html – willcodejavaforfood 2009-06-09 10:10:37

+1

所以它有效一次,但是當內部框架顯示它停止?是因爲剛打開的內部框架可能有焦點嗎? – willcodejavaforfood 2009-06-09 10:11:40

回答

3

聽起來像是你想有一個熱鍵,而不是一個按鍵偵聽器,以避免焦點問題。

// Get the KeyStroke for our hot key 

KeyStroke plus = KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, 0, true); 

// Get the input map for our component 
// In this case we are interested in key strokes in the focussed window 

InputMap inputMap = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); 

// Map the key stroke to our "action key" (see below) 

inputMap.put(plus, "my_action"); 

// Get the action map for our component 

ActionMap actionMap = panel.getActionMap(); 

// Add the required action listener to out action map 

actionMap.put("my_action", actionListener); 

http://helpdesk.objects.com.au/java/how-to-specify-a-hot-key-for-a-swing-application

+0

答案如何,而不是鏈接? – 2009-06-09 10:34:40

1

您將需要添加的按鍵偵聽器,正是有組件的焦點(許多組件實際上是複合材料)。

所以使用JComponent.registerKeyboardAction,條件爲WHEN_IN_FOCUSED_WINDOW。或者,使用JComponent.getInputMap(WHEN_IN_FOCUSED_WINDOW, true)JComponent.getActionMap(true),如registerKeyboardAction API文檔中所述。

0

請檢查是否引發運行時異常。可能是因爲顯示此對話框時出現錯誤線索,或者另一個問題可能會引發此異常。

也請考慮使用異步線程來顯示對話框而不是使用偵聽器線程。但這只是一個想法。