Document: addUndoableEditListener(UndoableEditListener listener)
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.UndoableEdit;
public class UndoStyleFrame extends JFrame {
protected UndoAct undoAction = new UndoAct();
protected RedoAct redoAction = new RedoAct();
public UndoStyleFrame() {
super();
setTitle("UndoStyleFrame");
JTextPane textPane = new JTextPane();
textPane.getDocument().addUndoableEditListener(undoAction);
textPane.getDocument().addUndoableEditListener(redoAction);
JMenu editMenu = new JMenu("Edit");
editMenu.add(new JMenuItem(undoAction));
editMenu.add(new JMenuItem(redoAction));
JMenuBar menuBar = new JMenuBar();
menuBar.add(editMenu);
setJMenuBar(menuBar);
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton(undoAction));
buttonPanel.add(new JButton(redoAction));
getContentPane().add(textPane, "Center");
getContentPane().add(buttonPanel, "South");
}
public class UndoAct extends AbstractAction implements UndoableEditListener {
private UndoableEdit edit;
public UndoAct() {
super("Undo");
setEnabled(false);
}
public void updateEnabled() {
setEnabled(edit.canUndo());
}
public void undoableEditHappened(UndoableEditEvent event) {
edit = event.getEdit();
putValue(NAME, edit.getUndoPresentationName());
updateEnabled();
}
public void actionPerformed(ActionEvent ae) {
edit.undo();
updateEnabled();
redoAction.updateEnabled();
}
}
public class RedoAct extends AbstractAction implements UndoableEditListener {
private UndoableEdit edit;
public RedoAct() {
super("Redo");
setEnabled(false);
}
public void updateEnabled() {
setEnabled(edit.canRedo());
}
public void undoableEditHappened(UndoableEditEvent event) {
edit = event.getEdit();
putValue(NAME, edit.getRedoPresentationName());
updateEnabled();
}
public void actionPerformed(ActionEvent ae) {
edit.redo();
updateEnabled();
undoAction.updateEnabled();
}
}
public static void main(String[] args) {
JFrame frame = new UndoStyleFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
Related examples in the same category