title: Java Listen to Button and Keyboard click
body: <p>How to listen to key pressed and trigger a JButton?</p>
  
  <p>For example:</p>
  
  <p>I have "A" JButton as the GUI on a panel. I have a buttonListener implemented on "aButton", that will change the screen to something else. I want this button to be triggered by both mouse click and keyboard pressed.</p>
  
  <p>How can I trigger this "A" JButton by pressing "a" on keyboard while having the buttonListener implemented as well?</p>
  
  <p>My current code cannot triggered the key event.</p>
  
  <pre><code>ButtonListener listener;
  KeyboardListener keyboardListener;
  private JButton aButton;
  
  public MyButtonPanel() {
      listener = new ButtonListener();
  
      aButton = new JButton ("A");
      aButton.setFont (BUTTON_TEXT);
      aButton.setPreferredSize (new Dimension (60,30));
      aButton.addActionListener (listener);
      aButton.addKeyListener (keyboardListener);
  
      setLayout (new BorderLayout());
      add (aButton, BorderLayout.CENTER);
  
  }
  
  private class KeyboardListener implements KeyListener
  {
      public void keyPressed(KeyEvent arg0) {
          char c = arg0.getKeyChar();
          System.out.println("Pressed " + c);
      }
  
      public void keyReleased(KeyEvent arg0) {
          char c = arg0.getKeyChar();
          System.out.println("Released " + c);
      }
  
      public void keyTyped(KeyEvent arg0) {
          char c = arg0.getKeyChar();
          System.out.println("Typed " + c);
      }
  
  }
  
   private class ButtonListener implements ActionListener {
    public void actionPerformed (ActionEvent event) {
      Object source = event.getSource();
  
      if (source == aButton) {
          System.out.println("This is a");
      }
    }
   }
  </code></pre>
  
  <p>}</p>