Organizing Actions in a Swing Application?

前端 未结 3 640
你的背包
你的背包 2021-01-02 18:03

My current application has a JFrame with about 15 actions stored as fields within the JFrame. Each of the actions is an anonymous class and some of them are pretty long.

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-02 18:19

    If it is possible that your actions could be reusable (e.g., from keyboard shortcuts, other menus, other dialogs, etc.) and especially if they can work directly on the underlying model (rather than on the UI), then it is generally better not to have them as anonymous classes.

    Rather, create a separate package, and create classes for each.

    Often, it also makes sense to not instantiate these directly but rather have some sort of a manager that defines constants and initializes and returns sets of actions, so that you could, for example, offer different action sets at different versions or set certain actions only for internal releases.

    Finally, check whether your actions can be refactored into a class hierarchy. They often can, which saves code replication, and also helps you add robustness (e.g., check for certain conditions before letting the action execute).

提交回复
热议问题