Java Reference
In-Depth Information
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.
The EditorGui represents a generic editor you might use in the PIM. Note that the class uses the ItemEditor
interface to entirely manage its edit window. It constructs a JPanel for its edit window, and places the
JComponent obtained by the call to getGUI inside. The Swing component provides all the edit capabilities for the
Contact , while the EditorGui provides control buttons and a JTextArea to display the state of the Contact
object.
Example A.24 EditorGui.java
1. import java.awt.Container;
2. import java.awt.event.ActionListener;
3. import java.awt.event.WindowAdapter;
4. import java.awt.event.ActionEvent;
5. import java.awt.event.WindowEvent;
6. import javax.swing.BoxLayout;
7. import javax.swing.JButton;
8. import javax.swing.JComponent;
9. import javax.swing.JFrame;
10. import javax.swing.JPanel;
11. import javax.swing.JTextArea;
12. public class EditorGui implements ActionListener{
13. private JFrame mainFrame;
14. private JTextArea display;
15. private JButton update, exit;
16. private JPanel controlPanel, displayPanel, editorPanel;
17. private ItemEditor editor;
18.
19. public EditorGui(ItemEditor edit){
20. editor = edit;
21. }
22.
23. public void createGui(){
24. mainFrame = new JFrame("Factory Pattern Example");
25. Container content = mainFrame.getContentPane();
26. content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
27.
28. editorPanel = new JPanel();
29. editorPanel.add(editor.getGUI());
30. content.add(editorPanel);
31.
Search WWH ::




Custom Search