Java 怎么为Swing组件启用撤消/重做功能

2019年8月18日21:59:32Java 怎么为Swing组件启用撤消/重做功能已关闭评论 177 1280字阅读4分16秒

1.简介

Java 怎么为Swing组件启用撤消/重做功能?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import javax.swing.text.Document;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;

public class Main {
    
    public static UndoManager enableUndoManagement(Document doc,
            JComponent component) {

        final UndoManager manager = new UndoManager();
        doc.addUndoableEditListener(manager);

        
        Action undoAction = new AbstractAction() {
            private static final long serialVersionUID = 8573395919242317325L;

            @Override
            public void actionPerformed(ActionEvent evt) {
                try {
                    manager.undo();
                } catch (CannotUndoException e) {
                    
                }
            }
        };
        component.getInputMap(JComponent.WHEN_FOCUSED).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_Z,
                        InputEvent.CTRL_DOWN_MASK), undoAction);

        
        Action redoAction = new AbstractAction() {
            private static final long serialVersionUID = 8340075601425828378L;

            @Override
            public void actionPerformed(ActionEvent evt) {
                try {
                    manager.redo();
                } catch (CannotRedoException e) {
                    
                }
            }
        };
        component.getInputMap(JComponent.WHEN_FOCUSED).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_Y,
                        InputEvent.CTRL_DOWN_MASK), redoAction);

        return manager;
    }
}

 
继续阅读
编程十万个怎么办