Java Reference
In-Depth Information
The following code shows the implementation for one of the PIM items, Contact . The Contact class defines two
attributes: the name of the person and their relationship with the user. These attributes provide a sample of some
of the information, which could be included in an entry in the PIM.
Example 1.16 Contact.java
1. import java.awt.GridLayout;
2. import java.io.Serializable;
3. import javax.swing.JComponent;
4. import javax.swing.JLabel;
5. import javax.swing.JPanel;
6. import javax.swing.JTextField;
7.
8. public class Contact implements Editable, Serializable {
9. private String name;
10. private String relationship;
11.
12. public ItemEditor getEditor() {
13. return new ContactEditor();
14. }
15.
16. private class ContactEditor implements ItemEditor, Serializable {
17. private transient JPanel panel;
18. private transient JTextField nameField;
19. private transient JTextField relationField;
20.
21. public JComponent getGUI() {
22. if (panel == null) {
23. panel = new JPanel();
24. nameField = new JTextField(name);
25. relationField = new JTextField(relationship);
26. panel.setLayout(new GridLayout(2,2));
27. panel.add(new JLabel("Name:"));
28. panel.add(nameField);
29. panel.add(new JLabel("Relationship:"));
30. panel.add(relationField);
31. } else {
32. nameField.setText(name);
33. relationField.setText(relationship);
34. }
35. return panel;
36. }
37.
38. public void commitChanges() {
39. if (panel != null) {
40. name = nameField.getText();
41. relationship = relationField.getText();
42. }
43. }
44.
45. public String toString(){
46. return "\nContact:\n" +
47. " Name: " + name + "\n" +
48. " Relationship: " + relationship;
49. }
50. }
51. }
Contact implements the Editable interface, and provides its own editor. That editor only applies to the Contact
class, and needs to change certain attributes of the Contact , it is best to use an inner class. The inner class has
direct access to the attributes of the outer class. If you used another (non-inner) class, Contact would need to
provide accessor and mutator methods, making it harder to restrict access to the object's private data.
Note that the editor itself is not a Swing component, but only an object that can serve as a factory for such a
component. The greatest benefit is that you can serialize and send this object across a stream. To implement this
feature, declare all Swing component attributes in ContactEditor transient—they're constructed when and
where they're needed.
 
Search WWH ::




Custom Search