📄 reundo.java
字号:
import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.Document;
import javax.swing.undo.*;
public class ReUndo implements UndoableEditListener,MouseListener{
public ReUndo() { }
UndoManager undom = new UndoManager(); //
UndoableEdit undoableEdit; //
JButton redo = new JButton("Redo"); //用于重做按钮
JButton undo = new JButton("Undo"); //用于撤销按钮
public static void main(String args[]){
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (InstantiationException ex) { }
catch (IllegalAccessException ex) { }
catch (ClassNotFoundException ex) { }
catch (UnsupportedLookAndFeelException ex) { }
ReUndo ru = new ReUndo();
JFrame frame = new JFrame("RedoAndUndo");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(10,10,500,500);
JTextArea area = new JTextArea();
area.setVisible(true);
Document doc = area.getDocument(); //取得一个文本容器
doc.addUndoableEditListener(ru); //为此文本容器添加可撤销操作监听
JPanel p = new JPanel();
p.setVisible(true);
ru.redo.setSize(120,25);
ru.redo.setVisible(true);
ru.redo.addMouseListener(ru);
ru.undo.setSize(120,25);
ru.undo.setVisible(true);
ru.undo.addMouseListener(ru);
frame.add(area,BorderLayout.CENTER);
frame.add(p,BorderLayout.SOUTH);
p.add(ru.redo);
p.add(ru.undo);
}
public void undoableEditHappened(UndoableEditEvent e) {
undoableEdit = e.getEdit(); //取得每次操作的可撤销操作的数据
undom.addEdit(undoableEdit); //将数据存放到UndoManager中
}
public void mouseClicked(MouseEvent e) {
if(e.getComponent() == redo){
if(undom.canRedo()){undom.redo();} //判断此次能否能实现redo操作,是则执行.
if(undom.canRedo() == false) {redo.setEnabled(false);} //判断下次能否能实现redo操作,否则使redo按钮不可用.
if(undom.canUndo()){undo.setEnabled(true);} //判断undo操作是否能实现,是则使undo按钮可用.
}else if(e.getComponent() == undo){
if(undom.canUndo()){undom.undo();} //判断此次能否能实现undo操作,是则执行.
if(undom.canUndo() == false){undo.setEnabled(false);}//判断下次能否能实现undo操作,否则使undo按钮不可用.
if(undom.canRedo()){redo.setEnabled(true);}//判断redo操作是否能实现,是则使redo按钮可用
}
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -