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

2019年8月18日21:59:32 评论 21

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;
    }
}

 

3.总结

示例代码演示了 Java 怎么为Swing组件启用撤消/重做功能,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: