我构建了一个 JMenu,现在想要添加菜单项。所以我所拥有的是:
- JMenu jm
- 行动
现在,为了添加一个菜单项触发操作行为:如果我使用它会有什么不同
jm.add(act);
或
jm.add(new JMenuItem(act));
?
最佳答案
根据 JMenu.add(Action) 的文档,它会为您创建一个新的菜单项,因此它们本质上是相同的。所以这最终是一种方便的方法。
但是,它还指出:
As of 1.3, this is no longer the preferred method for adding Actions to a container. Instead it is recommended to configure a control with an action using setAction, and then add that control directly to the Container.
如果我们查看 JMenu 的源代码(从 Google Code Search 检索),add(Action)
方法如下所示:
public JMenuItem add(Action a) {
JMenuItem mi = createActionComponent(a);
mi.setAction(a);
add(mi);
return mi;
}
所以不,没有太大区别。但无论如何,我仍然会遵循文档的建议,手动进行控制。
关于java - J菜单 : add(Action a) vs add(new JMenuItem(Action a),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4839164/