Design Patterns Java™ Workbook

(Michael S) #1
Appendix B. Solutions

Command (Chapter 24)............................................................................................................................


SOLUTION 24.1....................................................................................................................................


Java Swing applications commonly apply the MEDIATOR pattern, registering a single object to
receive all GUI events. This object mediates the interaction of the components and translates
user input into commands for business domain objects.


SOLUTION 24.2....................................................................................................................................


Your code should look something like:


protected JMenu fileMenu()
{
if (fileMenu == null)
{
fileMenu = new JMenu("File");
Font f = SwingFacade.getStandardFont();
fileMenu.setFont(f);


JMenuItem save = new JMenuItem("Save");
save.setFont(f);
fileMenu.add(save);
save.addActionListener
(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
save();
}
}
);


JMenuItem load = new JMenuItem("Load");
load.setFont(f);
fileMenu.add(load);
load.addActionListener
(
new ActionListener()
{
public void actionPerformed(ActionEvent e) {
load();
}
}
);
}
return fileMenu;
}


Although the actionPerformed() method requires an ActionEvent argu-ment, you can
safely ignore it. The fileMenu() code registers a single in-stance of an anonymous class
with the Save menu item and a single instance of another anonymous class with the Load
menu item. When these methods are called, there is no doubt about the source of the event.

Free download pdf