Java Reference
In-Depth Information
Mediator
In this example, a Mediator manages communication among the panels of a graphical user interface. The basic
design of this GUI uses one panel to select a Contact from a list, another panel to allow editing, and a third panel
to show the current state of the Contact. The Mediator interacts with each panel, calling the appropriate methods
to keep each part of the GUI up to date.
The class MediatorGui creates the main window and the three panels for the application. It also creates a
mediator and matches it with the three child panels.
Example A.74 MediatorGui.java
1. import java.awt.Container;
2. import java.awt.event.WindowEvent;
3. import java.awt.event.WindowAdapter;
4. import javax.swing.BoxLayout;
5. import javax.swing.JButton;
6. import javax.swing.JFrame;
7. import javax.swing.JPanel;
8. public class MediatorGui{
9. private ContactMediator mediator;
10.
11. public void setContactMediator(ContactMediator newMediator){ mediator = newMediator; }
12.
13. public void createGui(){
14. JFrame mainFrame = new JFrame("Mediator example");
15. Container content = mainFrame.getContentPane();
16. content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
17. ContactSelectorPanel select = new ContactSelectorPanel(mediator);
18. ContactDisplayPanel display = new ContactDisplayPanel(mediator);
19. ContactEditorPanel edit = new ContactEditorPanel(mediator);
20. content.add(select);
21. content.add(display);
22. content.add(edit);
23. mediator.setContactSelectorPanel(select);
24. mediator.setContactDisplayPanel(display);
25. mediator.setContactEditorPanel(edit);
26. mainFrame.addWindowListener(new WindowCloseManager());
27. mainFrame.pack();
28. mainFrame.setVisible(true);
29. }
30. private class WindowCloseManager extends WindowAdapter{
31. public void windowClosing(WindowEvent evt){
32. System.exit(0);
33. }
34. }
35. }
36.
37.
The simplest of the GUI panels is the ContactDisplayPanel . It has a method called contactChanged that
updates its display region with the values of the Contact argument.
Example A.75 ContactDisplayPanel.java
1. import java.awt.BorderLayout;
2. import javax.swing.JPanel;
3. import javax.swing.JScrollPane;
4. import javax.swing.JTextArea;
5. public class ContactDisplayPanel extends JPanel{
6. private ContactMediator mediator;
7. private JTextArea displayRegion;
8.
9. public ContactDisplayPanel(){
10. createGui();
11. }
12. public ContactDisplayPanel(ContactMediator newMediator){
13. setContactMediator(newMediator);
14. createGui();
15. }
16. public void createGui(){
17. setLayout(new BorderLayout());
18. displayRegion = new JTextArea(10, 40);
19. displayRegion.setEditable(false);
 
Search WWH ::




Custom Search