Java Reference
In-Depth Information
41. public void setOrganization(String newOrganization){ organization = newOrganization; }
42.
43. public void updateModel(String newFirstName, String newLastName,
44. String newTitle, String newOrganization){
45. if (!isEmptyString(newFirstName)){
46. setFirstName(newFirstName);
47. }
48. if (!isEmptyString(newLastName)){
49. setLastName(newLastName);
50. }
51. if (!isEmptyString(newTitle)){
52. setTitle(newTitle);
53. }
54. if (!isEmptyString(newOrganization)){
55. setOrganization(newOrganization);
56. }
57. updateView();
58. }
59.
60. private boolean isEmptyString(String input){
61. return ((input == null) || input.equals(""));
62. }
63.
64. private void updateView(){
65. Iterator notifyViews = contactViews.iterator();
66. while (notifyViews.hasNext()){
67. ((ContactView)notifyViews.next()).refreshContactView(firstName, lastName, title,
organization);
68. }
69. }
70. }
The ContactModel maintains an ArrayList of ContactView objects, updating them whenever the model data
changes. The standard behavior for all views is defined by the ContactView interface method
refreshContactView .
Example 4.2 ContactView.java
1. public interface ContactView{
2. public void refreshContactView(String firstName,
3. String lastName, String title, String organization);
4. }
Two views are used in this example. The first, ContactDisplayView , displays the updated model information but
does not support a controller, an example of “view-only” behavior.
Example 4.3 ContactDisplayView.java
1. import javax.swing.JPanel;
2. import javax.swing.JScrollPane;
3. import javax.swing.JTextArea;
4. import java.awt.BorderLayout;
5. public class ContactDisplayView extends JPanel implements ContactView{
6. private JTextArea display;
7.
8. public ContactDisplayView(){
9. createGui();
10. }
11.
12. public void createGui(){
13. setLayout(new BorderLayout());
14. display = new JTextArea(10, 40);
15. display.setEditable(false);
16. JScrollPane scrollDisplay = new JScrollPane(display);
17. this.add(scrollDisplay, BorderLayout.CENTER);
18. }
19.
20. public void refreshContactView(String newFirstName,
21. String newLastName, String newTitle, String newOrganization){
22. display.setText("UPDATED CONTACT:\nNEW VALUES:\n" +
23. "\tName: " + newFirstName + " " + newLastName +
24. "\n" + "\tTitle: " + newTitle + "\n" +
25. "\tOrganization: " + newOrganization);
26. }
27. }
Search WWH ::




Custom Search