Team usefulness when using JComponents

So, I am developing a program using the Swing library, and I obviously have buttons and menu items. Some of them should do the same things, and I thought that using the Command pattern should be a way to do this, for example. I have a Save button and a Save menu item, and they should implement the same save algorithm. The Command Pattern seems to be fine, but I can't get who the recipient is in all of this. Isn't it a command that should work on an object that implements some kind of “receiver interface”, so you can use different commands on different receivers associated with them? There seems to be no “receiver” in my template implementation. Another doubt is whether the team should be implemented as a singleton,since you could name its functions from different parts of the same project, and would it be easy to instantiate only once and make it statically invokable?

Thanks.

+4
source share
2 answers

"I obviously have buttons and menu items. Some of them should do the same."

As @nIcEcOw noted, what are they for Action. This answer shows exactly that.

As stated in How to use actions :

. , , , Action . Action - , -, , -, , , . , , , , , .

enter image description here

An Actions. Ont , . Action ActionCommand icon, . JMenuItem JToolBar Action . , .

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;

public class ActionTest {

    public ActionTest() {
        ImageIcon openIcon = new ImageIcon(
                ActionTest.class.getResource("/resources/image/open.gif"));
        ImageIcon saveIcon = new ImageIcon(
                ActionTest.class.getResource("/resources/image/save.gif"));
        ImageIcon newIcon = new ImageIcon(
                ActionTest.class.getResource("/resources/image/new.gif"));

        Action openAction = new AbstractAction("Open", openIcon) {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Open File");
            }
        };
        Action saveAction = new AbstractAction("Save", saveIcon) {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Save File");
            }
        };
        Action newAction = new AbstractAction("New", newIcon) {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("New File");
            }
        };

        JMenuItem openMenuItem = new JMenuItem(openAction);
        JMenuItem saveMenuItem = new JMenuItem(saveAction);
        JMenuItem newMenuItem = new JMenuItem(newAction);

        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        fileMenu.add(openMenuItem);
        fileMenu.add(saveMenuItem);
        fileMenu.add(newMenuItem);
        menuBar.add(fileMenu);

        JToolBar toolBar = new JToolBar();
        toolBar.add(Box.createHorizontalGlue());
        toolBar.setBorder(new LineBorder(Color.LIGHT_GRAY, 1));
        toolBar.add(newAction);
        toolBar.add(openAction);
        toolBar.add(saveAction);

        JFrame frame = new JFrame("Toolbar and Menu Test");
        frame.setJMenuBar(menuBar);
        frame.add(toolBar, BorderLayout.PAGE_START);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ActionTest();
            }
        });
    }
}

, , Action. . Action,

  • String
  • .

    private class MyAction extends AbstractAction {
    
        String name;
    
        public MyAction(String name, Icon icon) {
            super(name, icon);
            this.name = name;
        }
    
        public MyAction(String name, Icon icon, String desc,
                        Integer mnemonic, KeyStroke accelorator) {
            super(name, icon);
            putValue(Action.SHORT_DESCRIPTION, desc);
            putValue(Action.MNEMONIC_KEY, mnemonic);
            putValue(Action.ACCELERATOR_KEY, accelorator);
            this.name = name;
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            switch (name) {
                case "Open":
                    System.out.println("Open");
                    break;
                case "New":
                    System.out.println("New");
                    break;
                case "Save":
                    System.out.println("Save");
                    break;
            }
        }
    }
    

Action

Action newAction = new MyAction("New", newIcon,
            "Creates a new file",
            new Integer(KeyEvent.VK_N),
            KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));

. ActionCommand, , , , jtoolbar . , . , , Action JToolBar JMenu .

enter image description here

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ActionInterfaceDemo extends JFrame {

    public ActionInterfaceDemo() {
        ImageIcon openIcon = new ImageIcon(ActionInterfaceDemo.class.getResource("/resources/image/open.gif"));
        ImageIcon saveIcon = new ImageIcon(ActionInterfaceDemo.class.getResource("/resources/image/save.gif"));
        ImageIcon newIcon = new ImageIcon(ActionInterfaceDemo.class.getResource("/resources/image/new.gif"));

        Action openAction = new MyAction("Open", openIcon,
                "Opens a file",
                new Integer(KeyEvent.VK_O),
                KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
        Action saveAction = new MyAction("Save", saveIcon,
                "Saves a file",
                new Integer(KeyEvent.VK_S),
                KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
        Action newAction = new MyAction("New", newIcon,
                "Creates a new file",
                new Integer(KeyEvent.VK_N),
                KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));

        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        setJMenuBar(menuBar);
        menuBar.add(fileMenu);

        fileMenu.add(newAction);
        fileMenu.add(openAction);
        fileMenu.add(saveAction);


        JToolBar toolBar = new JToolBar("Alignment");
        toolBar.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        toolBar.add(Box.createHorizontalGlue());
        toolBar.add(newAction);
        toolBar.add(openAction);
        toolBar.add(saveAction);

        add(toolBar, BorderLayout.PAGE_START);
        add(new JScrollPane(new TextArea(10, 40)), BorderLayout.CENTER);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle("Action Interface Demo");
        pack();
        setLocationByPlatform(true);
        setVisible(true);
    }

    private class MyAction extends AbstractAction {

        String name;

        public MyAction(String name, Icon icon) {
            super(name, icon);
            this.name = name;
        }

        public MyAction(String name, Icon icon, String desc,
                Integer mnemonic, KeyStroke accelorator) {
            super(name, icon);
            putValue(Action.SHORT_DESCRIPTION, desc);
            putValue(Action.MNEMONIC_KEY, mnemonic);
            putValue(Action.ACCELERATOR_KEY, accelorator);
            this.name = name;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            switch (name) {
                case "Open":
                    System.out.println("Open");
                    break;
                case "New":
                    System.out.println("New");
                    break;
                case "Save":
                    System.out.println("Save");
                    break;
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new ActionInterfaceDemo();
            }
        });
    }
}

UPDATE

Action

, , , . ( ) , invokers (, ).

Swing Borland Delphi Action . , Action , , .. Action.

, Swing Actions

OP

"Command Pattern, , , , ".

, wiki

, : , , , .. - , . . , - , moveUp, , moveUp. , , .

Command Pattern

, , - , , .

, , Invoker: , , , .

, :

  • MenuItem ()
  • ( ), actionPerformed, , ,
  • .

wiki Java

+4

, Action, .

:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ActionExample {

    private JFrame frame;
    private JButton button;
    private JMenuItem exitItem;
    private Action commonActions;

    private class CommonActions extends AbstractAction {

        public CommonActions(String title, String desc) {
            super(title);
            putValue(SHORT_DESCRIPTION, desc);
        }

        @Override
        public void actionPerformed(ActionEvent ae) {
            JOptionPane.showMessageDialog(frame,
                "Closing Frame", "Information", JOptionPane.INFORMATION_MESSAGE);
            frame.dispose();
        }
    };

    private void displayGUI() {
        frame = new JFrame("Action Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);                

        commonActions = new CommonActions("Exit", "To Exit the Application");

        JPanel contentPane = new JPanel();
        button = new JButton();
        button.setAction(commonActions);
        contentPane.add(button);

        frame.setJMenuBar(getMenuBar());
        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JMenuBar getMenuBar() {
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");

        exitItem = new JMenuItem(commonActions);
        fileMenu.add(exitItem);
        menuBar.add(fileMenu);

        return menuBar;
    }

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                new ActionExample().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}

SINGLETON PATTERN ( ( , ))

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ActionExample {

    private JFrame frame;
    private JButton button;
    private JMenuItem exitItem;

    private void displayGUI() {
        frame = new JFrame("Action Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        CommonActions.setValues(frame);

        JPanel contentPane = new JPanel();
        button = new JButton();
        button.setAction(CommonActions.getInstance());
        contentPane.add(button);

        frame.setJMenuBar(getMenuBar());
        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JMenuBar getMenuBar() {
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");

        exitItem = new JMenuItem(CommonActions.getInstance());
        fileMenu.add(exitItem);
        menuBar.add(fileMenu);

        return menuBar;
    }

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                new ActionExample().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}

class CommonActions extends AbstractAction {

    private static CommonActions commonActions = null;
    private static JFrame frame = null;

    static {
        try {
            commonActions = new CommonActions("Exit", "To Exit the Application");
        } catch (Exception e) {
            throw new RuntimeException("BINGO, an error");
        }
    }

    private CommonActions(String title, String desc) {
        super(title);
        putValue(SHORT_DESCRIPTION, desc);
    }

    public static CommonActions getInstance() {
        return commonActions;
    }

    public static void setValues(JFrame f) {
        frame = f;
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        JOptionPane.showMessageDialog(frame,
            "Closing Frame", "Information", JOptionPane.INFORMATION_MESSAGE);
        frame.dispose();
    }
}
+2

Source: https://habr.com/ru/post/1524945/


All Articles