Undo and Redo Operations in Java
Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java.
Undo Redo Operations in Java Swing
Through the javax.swing.undo package, Swing offers the capabilities of Undo and Redo. Users can use the undo mechanisms to undo the most recent action they've taken, and they can use the redo mechanisms to redo the most recent action they undid. We have now developed a text area within our class that implements the UndoableEditListener interface from the javax.swing.event package in order to receive undoable edit events.
To inform the listeners that the undoable modifications occurred, the function undoableEditHappened(UndoableEditEvent e) is called. In this function, adding modifications to the UndoManager is the standard operation. You will discover how to use Java Swing's Undo Redo Operations in this section. The UndoManager compiles the changes made and using the buttons, we invoked the UndoManager's undo() and redo() methods to reverse modifications.
UndoRedoExpl.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.undo.*;
import javax.swing.text.*;
import javax.swing.event.*;
public class UndoRedoExpl extends JFrame {
JButton b0, b1, b2;
JTextArea a;
JScrollPane p;
JPanel p1;
UndoManager m = new UndoManager();
public UndoRedoExpl() {
p1 = new JPanel();
a = new JTextArea(6, 30);
p = new JScrollPane(a);
m = new UndoManager();
b0 = new JButton("Undo");
b1 = new JButton("Redo");
b2 = new JButton("Exit");
b0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
m.undo();
} catch (Exception ex) {
}
}
});
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
m.redo();
} catch (Exception ex) {
}
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
a.getDocument().addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent e) {
m.addEdit(e.getEdit());
}
});
p1.add(p);
p1.add(b0);
p1.add(b1);
p1.add(b2);
add(p1);
setVisible(true);
pack();
}
public static void main(String[] args) {
UndoRedoExpl o = new UndoRedoExpl();
}
}
Output:
