Search code examples
javaawtactionlistenerkeylistenerkeyevent

Pass button click event to actionPerformed on key press


I'm working on a Java assignment that has to be done using AWT. I want a button to trigger by pushing the enter key while the button is in focus. I figured out how to do this in Swing with the doClick() method, but this doesn't seem to work in AWT. So far I'm trying this:

button.addActionListener(this); // Passes value from a TextBox to actionPerformed() 

button.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
         if(e.getKeyCode()==KeyEvent.VK_ENTER) {
              actionPerformed(null);
         }
    } 
});

public void actionPerformed (ActionEvent e) {
     try {  
          if (e.getSource() == button) {
               // Stuff I want to happen
          } else if (e.getSource() == anotherButton) {
               // Other Stuff
          } else {     //third button
               // More stuff
          }
     } catch (NumberFormatException nfe) { 
          // Null argument in keyPressed triggers this
          // catches empty string exception from TextBox
     }
 }

As I mentioned with the comments, the null argument will trigger the catch. Does anyone have any idea what that argument might be for the button press or perhaps an altogether easier way to go about this? Thanks.

Edit - clarification: actionPerformed() does one of three things with input from a TextBox depending on which of three buttons is clicked. The try/catch is to catch empty string/format exceptions.


Solution

  • You can always have a method called something like onButtonPress(), which your actionPerformed can call, as well as your keyPressed.

      button.addActionListener(this);
    
        button.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
             if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                  onButtonPress();
             }
        } 
     });
    
    public void actionPerformed (ActionEvent e) {
        if (e.getSource() == button){
           onButtonPress();
        } 
     }
    
    private void onButtonPress(){
        // do something
    }