2015-02-10 292 views
0

我一直在試圖製作一個小程序,當用戶按下某個鍵時打印消息,但它不會打印該消息。以下是我的代碼:Keybindings not working - swing

public static void key() { 
    Main main = new Main(); 
    JFrame frame = new JFrame(); 
    JComponent component = frame.getRootPane(); 
    frame.getContentPane().add(main); 
    System.out.println("adad"); 

    Action test = new AbstractAction() { 
     public void actionPerformed(ActionEvent e) { 
      System.out.println("w has been pressed"); 
     } 
    }; 
    component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0),"test"); 
    component.getActionMap().put("test", test); 

} 

沒有錯誤,但按下「w」鍵時不會調用actionPerformed。我究竟做錯了什麼?我不知道這是否相關,但這裏是主要的方法,也許我在這裏做錯了什麼。

public static void main(String[] args) { 

    Main main = new Main(); 
    JFrame frame = new JFrame(); 
    frame.add(main); 
    frame.pack(); 
    frame.setTitle("Test"); 
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); 
    frame.setResizable(false); 
    frame.setLayout(new BorderLayout()); 
    key(); 
    frame.setVisible(true); 
    frame.add(frame, BorderLayout.CENTER); 
} 
+0

爲了更好地幫助越早,張貼[MCVE](http://stackoverflow.com/help/ (最小完整可驗證示例)或[SSCCE](http://www.sscce.org/)(簡短的,獨立的,正確的示例)。 – 2015-02-10 00:39:25

回答

2

你已經創建了一個第二幀這是不是在屏幕上,它的鍵綁定綁定上也可見......

正如我昨天所說,關鍵綁定必須通過組件註冊其連接到(其連接到本地對等體之一)可顯示組件才能工作

如果您嘗試使用更多的東西一樣......

public static void key(JComponent component) { 
    Action test = new AbstractAction() { 
     public void actionPerformed(ActionEvent e) { 
      System.out.println("w has been pressed"); 
     } 
    }; 
    component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "test"); 
    component.getActionMap().put("test", test); 

} 

,並通過EIT的JFrame或它的一個她實例的子組件(如maincontentPane)從public static void main(...)方法,它應該工作

+0

終於!謝謝您的幫助。現在正常工作 – Ky6000 2015-02-10 00:50:54

+0

@ Ky6000現在你明白了一個[可運行的示例](https://stackoverflow.com/help/mcve)的重要性,它可以證明你的問題。這會減少混淆和更好的反應。我記得昨天看到的代碼並沒有確定'JComponent'的來源。您可以提供的環境越好,我們就可以更好地解決您的問題 – MadProgrammer 2015-02-10 00:53:08