定义内部类中的按钮动作Vs定义秋千中的公共类按钮动作 [英] define button actions in inner class Vs define button actions in public class in swing

查看:72
本文介绍了定义内部类中的按钮动作Vs定义秋千中的公共类按钮动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对话框,其中有四个按钮,分别是新建,保存,删除,取消。现在,每个人都需要执行自己的动作。因此,我定义了一个单独的类,该类实现了一个 ActionListener 。我已使用此类来执行每个按钮操作。

I have a dialog, which have four buttons say New, Save, Delete, Cancel. Now each of these need to perform their action. So I have defined a separate class which implements an ActionListener. I have used this class to perform each of the button action.

public class MyClass implements ActionListener {
  public void actionPerformed(ActionEvent e) { 
   if(e.getActionCommand().toString() == "OK") {
        // Code
   } else if( .. ){

   }
  }
}

我所做的是,我定义了一个内部类,该类曾经用于执行相同的功能。但是我没有得到的是编写单独类的最佳实践还是使用内部类的最佳实践。建议我在公开课上写作,以便明天有人可以使用该课来执行他们的动作。所以我有以下问题,

What I have done is, I defined an inner class which I used to do the same functionality. But what I was not getting is, is it best practice to write a separate class or is it best to use inner class. I was suggested to write in a public class so tomorrow some one can use this class to perform their action. So I have the following questions,


  1. 如果该功能未由任何对象调用(我不能说),则我可以在内部类中编写它吗?或

  1. If the functionality is not called by any object (which I can't say) then I can write it in inner class? OR

总是编写一个执行该对话框动作的内部类是一种好习惯吗?

Is it a good practice always to write inner class which performs the actions of that dialog?


推荐答案

这些问题没有通用答案。如果 actionPerformed()中的代码是一行,则编写整个类文件通常是多余的。

There is no general answer to these questions. If the code in actionPerformed() is one line, writing a whole class file is usually overkill.

代码更复杂,可能适合重用,但是随着代码的增长,它也变得更加具体(因此您无法再使用它)。

If the code is more complex, it might be suitable to reuse but as the code grows, it also gets more specific (so you can't reuse it anymore).

尝试请遵循以下方法:


  • 从彼此独立的简单块中构建应用程序。

  • 通过编写连接块的代码来配置应用程序。

因此,在您的情况下,您可以使用辅助方法来完成工作。将它们包装在摇摆动作 s ;

So in your case, you could have helper methods which do the work. Wrap them in Swing Actions; this allows you to use them in all kinds of buttons and menus.

请尝试将尽可能多的工作移到助手中,以使操作变得非常简单。如有疑问,请问自己:这段代码是工作的一部分吗?每个人都需要这样做吗?

Try to move as much work as possible into the helpers so that the actions become really simple. If in doubt, ask yourself: Is this code part of the work? Does everyone need to do this?

如果是,那么代码应该进入工作/帮助类。

If yes, then the code should go into a work/helper class.

如果是与UI相关的检查(可见/启用),转换(字符串到数字),验证等,则应该执行操作。

If it's things like UI related checks (visible/enabled), conversion (string to number), validation, etc., it should go into the action.

这篇关于定义内部类中的按钮动作Vs定义秋千中的公共类按钮动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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