2. Explain the Swing Action architecture


The Swing Action architecture is used to implement shared behaviour between two or more user interface components. For example, the menu items and the tool bar buttons will be performing the same action no matter which one is clicked. Another distinct advantage of using actions is that when an action is disabled then all the components, which use the Action, become disabled.

Design pattern: The javax.swing.Action interface extends the ActionListener interface and is an abstraction of a command that does not have an explicit UI component bound to it. The Action architecture is an implementation of a command design pattern. This is a powerful design pattern because it allows the separation of controller logic of an application from its visual representation. This allows the application to be easily configured to use different UI elements without having to re-write the control or call-back logic.

Defining action classes:

class FileAction extends AbstractAction {

//Constructor

FileAction(String name) {

super(name);

}

public void actionPerformed(ActionEvent ae){

//add action logic here

}

}

To add an action to a menu bar:

JMenu fileMenu = new JMenu(“File”);

FileAction newAction = new FileAction(“New”);

JMenuItem item = fileMenu.add(newAction);

item.setAccelaror(KeyStroke.getKeyStroke(‘N’, Event.CTRL_MASK));

To add action to a toolbar

private JToolBar toolbar = new JToolBar();

toolbar.add(newAction);

So, an action object is a listener as well as an action.


No comments:

Post a Comment