如何使 ActionEvent 和 KeyEvent 触发相同的操作?
我正在编写一个小程序,想要弄清楚如何使按钮和按键事件覆盖相同的代码位。对于这个问题,我将这个按钮称为 fireButton
。操作事件的代码当然会如下所示:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == fireButton) {
//all the code that pressing button executes
}
}
现在,我想按“enter”键来执行操作事件处理的相同代码,但我不想在 中再次重写所有代码keyPressed
方法。
具体来说,我正在编写一个战舰程序,“Fire”按钮从两个文本字段获取输入,处理异常,并将输入作为参数传递给在网格中的特定方块处触发的方法。理想情况下,按 Enter 键的功能与按开机按钮的功能相同。有没有办法让某个方法调用 actionPerformed
方法?如果不是,那么解决该问题的优雅方法是什么?
I'm writing an applet and want to figure out how to make a button and a key event cover the same bit of code. For this question, I'll call this button fireButton
. The code for the action event would of course look like this:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == fireButton) {
//all the code that pressing button executes
}
}
Now, I want pressing the 'enter' key to perform the same code that the action event handles, but I do not want to rewrite all the code again in a keyPressed
method.
To be specific, I'm writing a battleship program, and the 'Fire' button takes input from two textFields, handles exceptions, and passes the input as parameters to a method that fires at a particular square in the grid. Ideally, pressing the enter key would function the same way as if I had pressed the fire button. Is there a way to make a certain method call an actionPerformed
method? If not, what would be an elegant solution to the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
阅读 Swing 教程。有以下部分:
如果您只是谈论使用 Enter 键调用“Fire”按钮,请查看 输入键和按钮有多种方法。
Read the Swing tutorial. There are sections on:
If you are just talking about invoking the "Fire" button with the enter key then check out Enter Key and Button for a couple of approaches.
我建议您将所有代码放在一个单独的方法中,该方法接收来自事件的所有相关数据(如果有)作为参数:
如果您不需要来自事件的任何数据,那就更容易了;)
这样,您只需为这两个事件编写一次代码即可。这是一种通用的面向对象方法。
希望这有帮助。
I suggest you put all the code in a separate method that receives all the relevant data from the event (if any) as parameters:
If you don't need any data from the event its even easier ;)
This way you just write your code once for both events. It's a general OO aproach.
Hope this helps.
借用 MVC 我建议你有一个控制器类来处理这些类型的请求。然后您所要做的就是委托给每个事件处理程序中的控制器。
像这样:
如果您发布相关代码,我可以提出进一步的建议。
Borrowing from MVC I would recommend you have a controller class which handles these sorts of requests. Then all you have to do is delegate to the controller in each event handler.
Like so:
If you post relevant code I can make further suggestions.