在GUI组件上使用可重用操作的最佳实践

uri*_*iel 12 java swing action

我尝试了如何在我的Swing应用程序中使Action可恢复的不同之处.我不是重量级,1000多个线类(有很多内部/非类)的朋友,并尝试将我的代码分成多个类.从而使它们易于重复使用和更换.

为了在我为每个Action创建的应用程序中重用相同的Actions,它们在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...");
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

期待您的建议.提前致谢.

cam*_*ckr 2

这是一个好的选择实践(特别是使用静态内部类)吗?

这是大部分基本 Swing 代码的实现方式。

例如,看一下 DefaultEditorKit 的源代码,其中定义了所有操作。