Java Reference
In-Depth Information
75. update.addActionListener(controller);
76. exit.addActionListener(new ExitHandler());
77.
78. setLayout(new BorderLayout());
79. add(editPanel, BorderLayout.CENTER);
80. add(controlPanel, BorderLayout.SOUTH);
81. }
82.
83. public Object getUpdateRef(){ return update; }
84. public String getFirstName(){ return firstName.getText(); }
85. public String getLastName(){ return lastName.getText(); }
86. public String getTitle(){ return title.getText(); }
87. public String getOrganization(){ return organization.getText(); }
88.
89. public void refreshContactView(String newFirstName,
90. String newLastName, String newTitle,
91. String newOrganization){
92. firstName.setText(newFirstName);
93. lastName.setText(newLastName);
94. title.setText(newTitle);
95. organization.setText(newOrganization);
96. }
97.
98. private class ExitHandler implements ActionListener{
99. public void actionPerformed(ActionEvent event){
100. System.exit(0);
101. }
102. }
103. }
The updates to the model are possible due to the controller associated with the ContactEditView . In this example,
Java event-handling features (and by extension the Observer pattern) manage communication between the
ContactEditView and its associated Controller. ContactEditController updates the ContactModel when
the update behavior is triggered by the ContactEditView , calling the method updateModel with new data
provided by the editable fields of its associated view.
Example 4.5 ContactEditController.java
1. import java.awt.event.*;
2.
3. public class ContactEditController implements ActionListener{
4. private ContactModel model;
5. private ContactEditView view;
6.
7. public ContactEditController(ContactModel m, ContactEditView v){
8. model = m;
9. view = v;
10. }
11.
12. public void actionPerformed(ActionEvent evt){
13. Object source = evt.getSource();
14. if (source == view.getUpdateRef()){
15. updateModel();
16. }
17. }
18.
19. private void updateModel(){
20. String firstName = null;
21. String lastName = null;
22. if (isAlphabetic(view.getFirstName())){
23. firstName = view.getFirstName();
24. }
25. if (isAlphabetic(view.getLastName())){
26. lastName = view.getLastName();
27. }
28. model.updateModel( firstName, lastName,
29. view.getTitle(), view.getOrganization());
30. }
31.
32. private boolean isAlphabetic(String input){
33. char [] testChars = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
34. for (int i = 0; i < testChars.length; i++){
35. if (input.indexOf(testChars[i]) != -1){
36. return false;
37. }
38. }
39. return true;
Search WWH ::




Custom Search