Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, so basically making an object that encapsulates the behavior and other information that is needed when an action takes place can be seen as using the <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="nofollow noreferrer">command pattern</a>.</p> <p>The Wikipedia article linked above uses the <a href="http://java.sun.com/javase/6/docs/api/javax/swing/Action.html" rel="nofollow noreferrer"><code>Action</code></a> interface as an example of the command pattern in Swing. The <code>Action</code> interface is a subinterface of <a href="http://java.sun.com/javase/6/docs/api/java/awt/event/ActionListener.html" rel="nofollow noreferrer"><code>ActionListener</code></a>, so a class that implements <code>Action</code> will have to implement the <code>actionPerformed</code> method.</p> <p>Therefore, a class implementing <code>Action</code> will be encapsulating some operations which will be performed when an action occurs. And that class itself can be seen to follow the command pattern.</p> <p>When it comes to the implementation, in general, an <a href="http://java.sun.com/javase/6/docs/api/javax/swing/AbstractAction.html" rel="nofollow noreferrer"><code>AbstractAction</code></a> can be easier to use than implementing <code>Action</code> as it has several methods that needs to be overridden. An example using <code>AbstractAction</code> can be:</p> <pre><code>class MySpecialAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { // Perform operations. } } </code></pre> <p>The <code>MySpecialAction</code> is a command pattern object -- it has the behavior it must exhibit when an action takes place. When instantiating the above class, one could try the following:</p> <pre><code>MySpecialAction action = new MySpecialAction("Special Action", mySpecialIcon); </code></pre> <p>Then, the action can be registered to multiple components, such as <code>JButton</code>s, <code>JMenuItem</code>s and such. In each case, the same <code>MySpecialAction</code> object will be called:</p> <pre><code>JMenuItem specialMenuItem = new JMenuItem(action); /* ... */ JButton b = new JButton(action); </code></pre> <p>In both cases, the action that is associated with each component, the button and the menu item, refer to the same <code>MySpecialAction</code> action object, or command. As we can see, the <code>MySpecialAction</code> object is functioning as a object following the command pattern, as it encapsulates some action to be performed at a the time when an action takes place.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload