将按钮单击事件传递给操作在按键时执行 [英] Pass button click event to actionPerformed on key press

查看:93
本文介绍了将按钮单击事件传递给操作在按键时执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理必须使用AWT完成的Java分配.我希望按钮在焦点对准时按Enter键来触发.我想出了如何使用doClick()方法在Swing中执行此操作,但这在AWT中似乎不起作用.到目前为止,我正在尝试:

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
     }
 }

正如我在评论中提到的那样,null参数将触发捕获.是否有人知道该按钮按下的论点是什么,或者可能是一种更简单的解决方法?谢谢.

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.

编辑-澄清:actionPerformed()使用TextBox的输入来完成三件事之一,具体取决于单击了三个按钮中的哪个按钮. try/catch用于捕获空的字符串/格式异常.

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.

推荐答案

您总是可以拥有一个名为onButtonPress()的方法,您的actionPerformed可以调用它,以及您的keyPressed.

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
}

这篇关于将按钮单击事件传递给操作在按键时执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆