《Java2图形设计卷II:Swing》配套光盘源码
源代码在线查看: test.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.*;
public class Test extends JApplet {
private JTextArea textArea = new JTextArea("some content");
private Document document = textArea.getDocument();
private UndoManager undoManager = new UndoManager();
private UndoLastAction undoAction = new UndoLastAction();
private RedoAction redoAction = new RedoAction();
public Test() {
Container contentPane = getContentPane();
createMenu();
contentPane.add(textArea, BorderLayout.CENTER);
textArea.setFont(new Font("Dialog", Font.PLAIN, 24));
document.addUndoableEditListener(
new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent e){
undoManager.addEdit(e.getEdit());
undoAction.update();
redoAction.update();
}
});
}
private void createMenu() {
JMenuBar menuBar = new JMenuBar();
JMenu editMenu = new JMenu("Edit");
editMenu.add(new DefaultEditorKit.CutAction());
editMenu.add(new DefaultEditorKit.CopyAction());
editMenu.add(new DefaultEditorKit.PasteAction());
editMenu.addSeparator();
editMenu.add(undoAction);
editMenu.add(redoAction);
menuBar.add(editMenu);
setJMenuBar(menuBar);
}
class RedoAction extends AbstractAction {
public RedoAction() {
super("Redo");
update();
}
public void actionPerformed(ActionEvent e) {
undoManager.redo();
undoAction.update();
update();
}
public void update() {
boolean canRedo = undoManager.canRedo();
if(canRedo) {
setEnabled(true);
putValue(Action.NAME,
undoManager.getRedoPresentationName());
}
else {
setEnabled(false);
putValue(Action.NAME, "Redo");
}
}
}
class UndoLastAction extends AbstractAction {
public UndoLastAction() {
super("Undo");
update();
}
public void actionPerformed(ActionEvent e) {
undoManager.undo();
redoAction.update();
update();
}
public void update() {
boolean canUndo = undoManager.canUndo();
if(canUndo) {
setEnabled(true);
putValue(Action.NAME,
undoManager.getUndoPresentationName());
}
else {
setEnabled(false);
putValue(Action.NAME, "Undo");
}
}
}
}