我尝试了关于如何在我的 Swing 应用程序中使 Actions 可重用的不同方法。我不喜欢重量级的 1000 多个行类(有很多内部/匿名类)并尝试将我的代码分成多个类。从而使它们易于重复使用和更换。
为了在应用程序中重用相同的操作,我为每个操作创建了自己的类,以便在JMenuBar 和JToolBar 中使用它。请查看下面的最小示例。
这是一个很好的选择实践(尤其是使用静态内部类)吗?
public class SomeGUI extends JFrame {
public static void main(String[] args)
{
new SomeGUI();
}
public SomeGUI()
{
setJMenuBar(new MyMenuBar());
add(new MyToolBar());
setSize(400, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
class MyMenuBar extends JMenuBar {
JMenu menu = new JMenu("File");
public MyMenuBar()
{
add(menu);
menu.add(new JMenuItem(new Actions.NewAction("New", null, "New File", KeyEvent.VK_N)));
}
}
class MyToolBar extends JToolBar {
public MyToolBar()
{
add(new Actions.NewAction("New", null, "New File", KeyEvent.VK_N));
}
}
class Actions {
static class NewAction extends AbstractAction {
public NewAction(String name, ImageIcon icon, String desc, Integer mnemonic)
{
super(name, icon);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
}
@Override
public void actionPerformed(ActionEvent paramActionEvent)
{
System.out.println("do the new action...");
}
}
}
期待您的建议。提前致谢。
最佳答案
Is this a good choosen practice (esp. using static inner classes)?
这是大部分基本 Swing 代码的实现方式。
例如,查看 DefaultEditorKit 的源代码,其中定义了所有操作。
关于java - 在 GUI 组件上使用可重用操作的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7582633/