下面列出了怎么用javax.swing.undo.UndoableEdit的API类实例代码及写法,或者点击链接到github查看源代码。
public @Override void die() {
// Super of die()
int size = edits.size();
for (int i = size-1; i >= 0; i--)
{
UndoableEdit e = (UndoableEdit)edits.elementAt(i);
e.die();
}
alive2 = false;
// End super of die()
if (previous != null) {
previous.die();
previous = null;
}
}
@Test
public void setWeightsCreatesHistoryItem() throws UnparsableException {
Map<String, String> tokenWeights = new HashMap<>();
String oldWeight = "5";
when(mockArc.getWeightForToken(DEFAULT_TOKEN_ID)).thenReturn(oldWeight);
String newWeight = "51";
tokenWeights.put(DEFAULT_TOKEN_ID, newWeight);
controller.setWeights(tokenWeights);
UndoableEdit weightAction = new SetArcWeightAction<>(mockArc, DEFAULT_TOKEN_ID, oldWeight, newWeight);
UndoableEdit edit = new MultipleEdit(Arrays.asList(weightAction));
verify(listener).undoableEditHappened(argThat(Contains.thisAction(edit)));
}
private void jMenuItem_CutActionPerformed(ActionEvent evt) {
VectorLayer layer = (VectorLayer) _mapDocument.getActiveMapFrame().getMapView().getSelectedLayer();
List<Shape> selShapes = (List<Shape>)layer.getSelectedShapes();
UndoableEdit edit = (new MapViewUndoRedo()).new RemoveFeaturesEdit(_mapView, layer, selShapes);
currentUndoManager.addEdit(edit);
this.refreshUndoRedo();
for (Shape shape : selShapes) {
layer.editRemoveShape(shape);
}
this.jButton_EditRemoveFeature.setEnabled(false);
_mapView.paintLayers();
ShapeSelection shapeSelection = new ShapeSelection(selShapes);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(shapeSelection, null);
}
@Override
public String getUndoPresentationName() {
UndoableEdit last = lastEdit();
if (last != null) {
return last.getUndoPresentationName();
} else {
String name = getPresentationName();
if (!"".equals(name)) {
name = UIManager.getString("AbstractUndoableEdit.undoText")
+ " " + name;
} else {
name = UIManager.getString("AbstractUndoableEdit.undoText");
}
return name;
}
}
private static <T extends UndoableEdit> T getEditToBeUndoneRedoneOfType(EditorCookie ec, Class<T> type, boolean redone) {
UndoRedo ur;
if (ec instanceof CloneableEditorSupport &&
((ur = ((CloneableEditorSupport)ec).getUndoRedo()) instanceof UndoRedoManager))
{
UndoRedoManager urManager = (UndoRedoManager) ur;
UndoableEdit edit = urManager.editToBeUndoneRedone(redone);
if (type.isInstance(edit)) {
return type.cast(edit);
} else if (edit instanceof List) {
@SuppressWarnings("unchecked")
List<UndoableEdit> listEdit = (List<UndoableEdit>) edit;
for (int i = listEdit.size() -1; i >= 0; i--) { // Go from most wrapped back
edit = listEdit.get(i);
if (type.isInstance(edit)) {
@SuppressWarnings("unchecked") T inst = (T) edit;
return inst;
}
}
}
}
return null;
}
@Override
public UndoableEdit wrap(UndoableEdit edit, Document doc) {
WrapCompoundEdit wrapEdit = new WrapCompoundEdit();
wrapEdit.addEdit(edit);
wrapEdit.end();
return wrapEdit;
}
private void onZoomToLayerClick(ActionEvent e) {
LayerNode aLN = (LayerNode) _selectedNode;
MapLayer aLayer = aLN.getMapFrame().getMapView().getLayerByHandle(aLN.getLayerHandle());
MapView mapView = aLN.getMapFrame().getMapView();
Extent oldExtent = (Extent) mapView.getViewExtent().clone();
aLN.getMapFrame().getMapView().zoomToExtent(aLayer.getExtent());
UndoableEdit edit = (new MapViewUndoRedo()).new ZoomEdit(mapView, oldExtent, (Extent) mapView.getViewExtent().clone());
mapView.fireUndoEditEvent(edit);
}
UndoableEdit removeUpdate(int removeOffset, int removeLength) {
// The algorithm here is similar to the one in PlainDocument.removeUpdate().
// Unfortunately in case exactly a line element (or multiple line elements)
// the algorithm removes extra line that follows the end of removed area.
// That could be improved but compatibility with PlainDocument would be lost.
Edit edit = null;
int removeEndOffset = removeOffset + removeLength;
int line0 = getElementIndex(removeOffset);
int line1 = getElementIndex(removeEndOffset);
if (line0 != line1) {
// at least one line was removed
line1++; // will remove the line where remove ends as well
Element[] removeElements = new Element[line1 - line0];
copyElements(line0, line1, removeElements, 0);
Element[] addElements = new Element[] {
new LineElement(this,
((LineElement)removeElements[0]).getStartPosition(),
((LineElement)removeElements[removeElements.length - 1]).getEndPosition()
)
};
replace(line0, removeElements.length, addElements);
edit = new Edit(line0, removeElements, addElements);
}
// checkConsistency();
return edit;
}
private void onRemoveElementClick() {
UndoableEdit edit = (new MapLayoutUndoRedo()).new RemoveElementsEdit(this, _selectedElements);
this.fireUndoEditEvent(edit);
for (LayoutElement element : _selectedElements) {
removeElement(element);
}
_selectedElements.clear();
_startNewGraphic = true;
//paintGraphics();
this.repaintNew();
}
private void jMenuItem_InsertTitleActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
LayoutGraphic text = _mapDocument.getMapLayout().addText("Map Title", _mapDocument.getMapLayout().getWidth() / 2, 20, 12);
_mapDocument.getMapLayout().paintGraphics();
UndoableEdit edit = (new MapLayoutUndoRedo()).new AddElementEdit(_mapDocument.getMapLayout(), text);
undoManager.addEdit(edit);
this.refreshUndoRedo();
}
@Test
public void setNameCreatesUndoItem() {
String oldName = "oldName";
String newName = "newName";
when(transition.getId()).thenReturn(oldName);
controller.setId(newName);
UndoableEdit nameEdit = new ChangePetriNetComponentName(transition, oldName, newName);
verify(listener).undoableEditHappened(argThat(Contains.thisAction(nameEdit)));
}
private void jMenuItem_InsertLegendActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
LayoutLegend legend = _mapDocument.getMapLayout().addLegend(100, 100);
_mapDocument.getMapLayout().paintGraphics();
UndoableEdit edit = (new MapLayoutUndoRedo()).new AddElementEdit(_mapDocument.getMapLayout(), legend);
undoManager.addEdit(edit);
this.refreshUndoRedo();
}
private void jMenuItem_InsertScaleBarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
LayoutScaleBar sb = _mapDocument.getMapLayout().addScaleBar(100, 100);
_mapDocument.getMapLayout().paintGraphics();
UndoableEdit edit = (new MapLayoutUndoRedo()).new AddElementEdit(_mapDocument.getMapLayout(), sb);
undoManager.addEdit(edit);
this.refreshUndoRedo();
}
private void jMenuItem_InsertNorthArrowActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
LayoutNorthArrow na = _mapDocument.getMapLayout().addNorthArrow(200, 100);
_mapDocument.getMapLayout().paintGraphics();
UndoableEdit edit = (new MapLayoutUndoRedo()).new AddElementEdit(_mapDocument.getMapLayout(), na);
undoManager.addEdit(edit);
this.refreshUndoRedo();
}
private void jButton_FullExtentActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Extent oldExtent = (Extent) _mapView.getViewExtent().clone();
_mapView.zoomToExtent(_mapView.getExtent());
UndoableEdit edit = (new MapViewUndoRedo()).new ZoomEdit(_mapView, oldExtent, (Extent) _mapView.getViewExtent().clone());
zoomUndoManager.addEdit(edit);
this.refreshZoomUndoRedo();
}
/**
* Removes part of the content.
*
* @param where the starting position >= 0, where + nitems < length()
* @param nitems the number of characters to remove >= 0
* @return an UndoableEdit object for undoing
* @exception BadLocationException if the specified position is invalid
* @see AbstractDocument.Content#remove
*/
public UndoableEdit remove(int where, int nitems) throws BadLocationException {
if (where + nitems >= length()) {
throw new BadLocationException("Invalid remove", length() + 1);
}
String removedString = getString(where, nitems);
UndoableEdit edit = new RemoveUndo(where, removedString);
replace(where, nitems, empty, 0);
return edit;
}
@Test
public void incrementPlaceCounterCreatesHistoryItem() {
int oldCount = 7;
when(place.getTokenCount(DEFAULT_TOKEN_ID)).thenReturn(oldCount);
placeController.addTokenToPlace(DEFAULT_TOKEN_ID);
UndoableEdit changed = new ChangePlaceTokens(place, DEFAULT_TOKEN_ID, oldCount, oldCount + 1);
MultipleEdit edit = new MultipleEdit(Arrays.asList(changed));
verify(listener).undoableEditHappened(argThat(Contains.thisAction(edit)));
}
/**
* The same as super.editToBeUndone() just that we treat DocumentEvent.EventType.CHANGE
* the same way as true == edit.isSignificant().
*/
protected UndoableEdit editToBeUndone()
{
UndoableEdit ue = super.editToBeUndone();
if (ue == null)
{
return null;
}
int i = edits.indexOf(ue);
while (i >= 0)
{
UndoableEdit edit = edits.elementAt(i--);
if (edit.isSignificant())
{
if (edit instanceof AbstractDocument.DefaultDocumentEvent)
{
if (DocumentEvent.EventType.CHANGE != ((AbstractDocument.DefaultDocumentEvent)edit).getType())
{
return edit;
}
}
else
{
return edit;
}
}
}
return null;
}
@Override
public boolean matches(Object argument) {
UndoableEditEvent event = (UndoableEditEvent) argument;
UndoableEdit edit = event.getEdit();
return edit.equals(expectedEdit);
}
public @Override boolean replaceEdit(UndoableEdit anEdit) {
if (nonSignificant) { // Non-significant edit must be replacing
previousEdit = anEdit;
// Becomes significant
nonSignificant = false;
return true;
}
if (!undoMergeReset && mergeEditIndex >= 0) { // Only merge if this edit contains BaseDocumentEvent child item
List<UndoableEdit> thisEdits = getEdits();
BaseDocumentEvent thisMergeEdit = (BaseDocumentEvent) thisEdits.get(mergeEditIndex);
if (anEdit instanceof BaseDocument.AtomicCompoundEdit) {
BaseDocument.AtomicCompoundEdit anAtomicEdit
= (BaseDocument.AtomicCompoundEdit)anEdit;
List<UndoableEdit> anAtomicEditChildren = anAtomicEdit.getEdits();
for (int i = 0; i < anAtomicEditChildren.size(); i++) {
UndoableEdit child = (UndoableEdit)anAtomicEditChildren.get(i);
if (child instanceof BaseDocumentEvent && thisMergeEdit.canMerge((BaseDocumentEvent)child)) {
previousEdit = anEdit;
return true;
}
}
} else if (anEdit instanceof BaseDocumentEvent) {
BaseDocumentEvent evt = (BaseDocumentEvent)anEdit;
if (thisMergeEdit.canMerge(evt)) {
previousEdit = anEdit;
return true;
}
}
}
return false;
}
/**
* Removes part of the content.
*
* @param where the starting position >= 0, where + nitems < length()
* @param nitems the number of characters to remove >= 0
* @return an UndoableEdit object for undoing
* @exception BadLocationException if the specified position is invalid
* @see AbstractDocument.Content#remove
*/
public UndoableEdit remove(int where, int nitems) throws BadLocationException {
if (where + nitems >= length()) {
throw new BadLocationException("Invalid remove", length() + 1);
}
String removedString = getString(where, nitems);
UndoableEdit edit = new RemoveUndo(where, removedString);
replace(where, nitems, empty, 0);
return edit;
}
private KeyMasterTextArea(String text) {
super(text);
setFont(defaultFont);
setName("EDITOR");
setWrapStyleWord(false);
Document document = getDocument();
document.addUndoableEditListener(e -> {
UndoableEdit item = e.getEdit();
undoStack.push(item);
redoStack.clear();
updateUndoRedoAction();
});
setCaretPosition(0);
}
@Test
public void splittingCreatesHistoryItem() {
ArcPoint nextPoint = new ArcPoint(new Point2D.Double(10, 10), false);
ArcPoint splitPoint = new ArcPoint(new Point2D.Double(0, 0), true);
when(mockArc.getNextPoint(splitPoint)).thenReturn(nextPoint);
controller.splitArcPoint(splitPoint);
ArcPoint expected = new ArcPoint(new Point2D.Double(5, 5), true);
UndoableEdit addArcPointAction = new AddArcPathPoint<>(mockArc, expected);
verify(listener).undoableEditHappened(argThat(Contains.thisAction(addArcPointAction)));
}
/**
* Tries to set the functional expression of the rate
*
* @param expression new functional expression
* @throws InvalidRateException if the funcitonal expression is invalid because either it
* contains a syntax error or it references a component that does not exist
*/
public void setRate(String expression) throws InvalidRateException {
String oldRate = component.getExpression();
if (!oldRate.equals(expression)) {
FunctionalResults<Double> results = petriNet.parseExpression(expression);
if (results.hasErrors()) {
throw new InvalidRateException(results.getErrorString("\n"));
}
component.setExpression(expression);
UndoableEdit rateAction = new ChangeRateParameterRate(component, oldRate, expression);
registerUndoableEdit(rateAction);
}
}
/**
* Removes part of the content.
*
* @param where the starting position >= 0, where + nitems < length()
* @param nitems the number of characters to remove >= 0
* @return an UndoableEdit object for undoing
* @exception BadLocationException if the specified position is invalid
* @see AbstractDocument.Content#remove
*/
public UndoableEdit remove(int where, int nitems) throws BadLocationException {
if (where + nitems >= length()) {
throw new BadLocationException("Invalid remove", length() + 1);
}
String removedString = getString(where, nitems);
UndoableEdit edit = new RemoveUndo(where, removedString);
replace(where, nitems, empty, 0);
return edit;
}
@Test
public void setIdCreatesUndoItem() {
String oldId = "id";
String newId = "id2";
when(rateParameter.getId()).thenReturn(oldId);
rateParameterController.setId(newId);
UndoableEdit changed = new ChangePetriNetComponentName(rateParameter, oldId, newId);
verify(listener).undoableEditHappened(argThat(Contains.thisAction(changed)));
}
@Override
public UndoableEdit remove(int offset, int len) throws BadLocationException {
checkBoundsInDoc(offset, len);
UndoEdit edit = new UndoEdit(true, offset, getString(offset, len));
removeEdit(edit);
return edit;
}
/**
* Removes part of the content.
*
* @param where the starting position >= 0, where + nitems < length()
* @param nitems the number of characters to remove >= 0
* @return an UndoableEdit object for undoing
* @exception BadLocationException if the specified position is invalid
* @see AbstractDocument.Content#remove
*/
public UndoableEdit remove(int where, int nitems) throws BadLocationException {
if (where + nitems >= length()) {
throw new BadLocationException("Invalid remove", length() + 1);
}
String removedString = getString(where, nitems);
UndoableEdit edit = new RemoveUndo(where, removedString);
replace(where, nitems, empty, 0);
return edit;
}
/**
* Undoes every action in the multiple edits
*/
@Override
public void undo() {
super.undo();
for (UndoableEdit edit : multipleEdits) {
edit.undo();
}
}
private static void duplicate(Node[] nodes, int dimension, int direction) {
List<RADComponent> comps = FormUtils.getSelectedLayoutComponents(nodes);
RADVisualContainer parent = (comps != null) ? getParent(comps) : null;
if (parent != null) {
FormModel formModel = parent.getFormModel();
LayoutModel layoutModel = formModel.getLayoutModel();
Object layoutUndoMark = layoutModel.getChangeMark();
UndoableEdit layoutEdit = layoutModel.getUndoableEdit();
boolean autoUndo = true; // in case of unexpected error, for robustness
String[] sourceIds = new String[comps.size()];
String[] targetIds = new String[comps.size()];
int i = 0;
MetaComponentCreator creator = formModel.getComponentCreator();
try {
for (RADComponent comp : comps) {
RADComponent copiedComp = creator.copyComponent(comp, parent);
if (copiedComp == null) {
return; // copy failed...
}
sourceIds[i] = comp.getId();
targetIds[i] = copiedComp.getId();
i++;
}
FormEditor.getFormDesigner(formModel).getLayoutDesigner()
.duplicateLayout(sourceIds, targetIds, dimension, direction);
autoUndo = false;
} finally {
if (layoutUndoMark != null && !layoutUndoMark.equals(layoutModel.getChangeMark())) {
formModel.addUndoableEdit(layoutEdit);
}
if (autoUndo) {
formModel.forceUndoOfCompoundEdit();
}
}
}
}