Java Reference
In-Depth Information
11.
12. public void execute(){
13. oldLocation = appointment.getLocation();
14. newLocation = editor.getNewLocation();
15. appointment.setLocation(newLocation);
16. }
17. public void undo(){
18. appointment.setLocation(oldLocation);
19. }
20. public void redo(){
21. appointment.setLocation(newLocation);
22. }
23. }
The class provides the ability to change a location using the execute method. It provides undo behavior by storing
the previous value of the location and allowing a user to restore that value by calling the undo method. Finally, it
supports a redo method that enables users to restore the new location, if they happen to be very indecisive.
Support classes for this example include CommandGui , used to provide a user interface to edit the appointment
location.
Example A.44 CommandGui.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.JLabel;
11. import javax.swing.JPanel;
12. import javax.swing.JTextArea;
13. import javax.swing.JTextField;
14. public class CommandGui implements ActionListener, LocationEditor{
15. private JFrame mainFrame;
16. private JTextArea display;
17. private JTextField updatedLocation;
18. private JButton update, undo, redo, exit;
19. private JPanel controlPanel, displayPanel, editorPanel;
20. private UndoableCommand command;
21. private Appointment appointment;
22.
23. public CommandGui(UndoableCommand newCommand){
24. command = newCommand;
25. }
26.
27. public void setAppointment(Appointment newAppointment){
28. appointment = newAppointment;
29. }
30.
31. public void createGui(){
32. mainFrame = new JFrame("Command Pattern Example");
33. Container content = mainFrame.getContentPane();
34. content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
35.
36. editorPanel = new JPanel();
37. editorPanel.add(new JLabel("Location"));
38. updatedLocation = new JTextField(20);
39. editorPanel.add(updatedLocation);
40. content.add(editorPanel);
41.
42. displayPanel = new JPanel();
43. display = new JTextArea(10, 40);
44. display.setEditable(false);
45. displayPanel.add(display);
46. content.add(displayPanel);
47.
48. controlPanel = new JPanel();
49. update = new JButton("Update Location");
50. undo = new JButton("Undo Location");
51. redo = new JButton("Redo Location");
52. exit = new JButton("Exit");
53. controlPanel.add(update);
Search WWH ::




Custom Search