Java Swing 支持 撤销和恢复功能 ctrl+z ctrl+y

Java Swing 支持 撤销和恢复功能 ctrl+z ctrl+y.

package com.citi.wws.backup;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.undo.UndoManager;

public class UndoDemo extends JFrame implements ActionListener {

	static JTextArea textArea = new JTextArea();
	static JPanel pannel = new JPanel();
	static JButton unbtn = new JButton("撤销");
	static JButton rebtn = new JButton("恢复");
	static UndoManager undoManager = new UndoManager();

	UndoDemo() {

		super("撤销、恢复功能实例");
		setVisible(true);
		setSize(400, 300);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLayout(new BorderLayout(5, 5));

		pannel.setLayout(new FlowLayout(5));
		pannel.add(unbtn);
		pannel.add(rebtn);
		add(pannel, BorderLayout.NORTH);
		add(textArea, BorderLayout.CENTER);

		textArea.getDocument().addUndoableEditListener(undoManager);

		textArea.addKeyListener(new KeyListener() {

			@Override
			public void keyReleased(KeyEvent arg0) {
			}

			@Override
			public void keyPressed(KeyEvent evt) {
				if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_Z) {
					if (undoManager.canUndo()) {
						undoManager.undo();
					}
				}
				if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_Y) {
					if (undoManager.canRedo()) {
						undoManager.redo();
					}
				}
			}

			@Override
			public void keyTyped(KeyEvent arg0) {
			}
		});

		unbtn.addActionListener(this);
		rebtn.addActionListener(this);
	}

	public void actionPerformed(ActionEvent ent) {
		if (ent.getSource().equals(unbtn)) {
			if (undoManager.canUndo()) {
				undoManager.undo();
			}
		}
		if (ent.getSource().equals(rebtn)) {
			if (undoManager.canRedo()) {
				undoManager.redo();
			}
		}
	}

	public static void main(String[] args) {
		new UndoDemo();
	}
}


你可能感兴趣的:(Java Swing 支持 撤销和恢复功能 ctrl+z ctrl+y)