1 package jimm.datavision.gui.cmd; 2 import jimm.util.I18N; 3 import java.util.ArrayList ; 4 import javax.swing.JMenuItem ; 5 6 14 public class CommandHistory { 15 16 protected ArrayList commands; 17 protected int commandIndex; 18 22 protected int baselineIndex; 23 protected JMenuItem undoMenuItem; 24 protected JMenuItem redoMenuItem; 25 26 public CommandHistory() { 27 this(null, null); 28 } 29 30 public CommandHistory(JMenuItem undoMenuItem, JMenuItem redoMenuItem) { 31 this.undoMenuItem = undoMenuItem; 32 this.redoMenuItem = redoMenuItem; 33 commands = new ArrayList (); 34 commandIndex = 0; 35 baselineIndex = 0; 36 } 37 38 public void setMenuItems(JMenuItem undoMenuItem, JMenuItem redoMenuItem) { 39 this.undoMenuItem = undoMenuItem; 40 this.redoMenuItem = redoMenuItem; 41 } 42 43 44 public boolean canUndo() { return commandIndex > 0; } 45 46 47 public boolean canRedo() { return commandIndex < commands.size(); } 48 49 54 public void setBaseline() { baselineIndex = commandIndex; } 55 56 57 58 public boolean isChanged() { return baselineIndex != commandIndex; } 59 60 67 public synchronized void add(Command command) { 68 for (int i = commands.size() - 1; i >= commandIndex; --i) 70 commands.remove(i); 71 72 commands.add(command); 74 ++commandIndex; 75 76 updateMenu(); 77 } 78 79 86 public synchronized void perform(Command command) { 87 command.perform(); 88 add(command); 89 } 90 91 92 public synchronized void undo() { 93 if (commandIndex > 0) { 94 --commandIndex; 95 ((Command)commands.get(commandIndex)).undo(); 96 updateMenu(); 97 } 98 } 99 100 101 public synchronized void redo() { 102 if (commandIndex < commands.size()) { 103 ((Command)commands.get(commandIndex)).redo(); 104 ++commandIndex; 105 updateMenu(); 106 } 107 } 108 109 113 public String getUndoName() { 114 return commandIndex > 0 ? getCommandName(commandIndex - 1) : null; 115 } 116 117 121 public String getRedoName() { 122 return commandIndex < commands.size() 123 ? getCommandName(commandIndex) : null; 124 } 125 126 130 public String getCommandName(int index) { 131 Command cmd = null; 132 synchronized(this) { 133 cmd = (Command)commands.get(index); 134 } 135 return (cmd != null) ? cmd.getName() : null; 136 } 137 138 protected void updateMenu() { 139 if (undoMenuItem != null) 140 updateMenuItem(undoMenuItem, I18N.get("CommandHistory.undo"), 141 getUndoName(), canUndo()); 142 if (redoMenuItem != null) 143 updateMenuItem(redoMenuItem, I18N.get("CommandHistory.redo"), 144 getRedoName(), canRedo()); 145 } 146 147 protected void updateMenuItem(JMenuItem item, String verb, String cmdName, 148 boolean canDo) 149 { 150 if (canDo) 151 item.setText(verb + " " + cmdName); 152 else 153 item.setText(verb); 154 155 item.setEnabled(canDo); 156 } 157 158 } 159 | Popular Tags |