java中主窗口中创建菜单方法,使用Actions在Java中创建菜单,工具栏和其他组件的正确方法...

The naive way of writing building a menu in a Java Swing app is to do something like:

JMenu fileMenu = new JMenu("File");

JMenuItem openItem = new JMenuItem("Open...");

openItem.addActionListener(new ActionListener() { /* action listener stuff */ } )

fileMenu.addMenuItem(openItem);

A more experienced developer will recognize that actions can be accessed through a variety of mechanisms - menus, toolbar buttons, maybe even other workflows in the system. That person is more likely to write:

Action openAction = new AbstractAction();

openAction.setName("Open...");

openAction.addActionListener(new ActionListener() { /* action listener stuff */ } )

...

JMenuItem openItem = new JMenuItem(openAction);

My question is, what is the best way to manage these Action objects so they can be used across menus, toolbars, etc?

Create a factory class that returns specific actions?

Declare all of the actions as private static final Action in some utility class?

Take advantage of a Java application framework?

Something else?

解决方案

Applications that I have developed that need to use that same actions across menus, toolbars, and other buttons have been done using Swing Application Framework.

This framework will allow you to have a resource file where you can define all menu text, tooltips, and ICONS. I think the icons are the key, you do not have to load them yourself. Also, if you have any actions that you need to enable/disable you can override the method to control its state.

The website is worth the read.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值