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

来源:互联网 发布:网络dj歌曲最红最好听 编辑:程序博客网 时间:2024/05/22 17:16

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() {@Overridepublic void keyReleased(KeyEvent arg0) {}@Overridepublic 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();}}}@Overridepublic 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();}}


0 0
原创粉丝点击