Skip to content

Commit

Permalink
💄 Feature: Undo/Redo
Browse files Browse the repository at this point in the history
  • Loading branch information
alaabenfatma committed Jun 5, 2022
1 parent 568a2a8 commit ca2c728
Showing 1 changed file with 39 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,32 @@
import java.awt.Dimension;
import java.awt.Font;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.*;

public class EditorPane {

private JTextPane editor;
private JTextArea lineCounter;
private Font font;
private String title;

private UndoManager undoManager;
private int old_line_number;

public EditorPane(String title) {
this.editor = new JTextPane();
this.lineCounter = new JTextArea(10, 1);
this.font = new Font("Sanserif", Font.BOLD, 16);
this.undoManager = new UndoManager();
this.title = title;
this.initLineCounter();
this.initEditor();
Expand All @@ -42,6 +48,9 @@ private void initEditor() {
this.editor.setBorder(BorderFactory.createTitledBorder(this.title + " editor:"));
this.editor.setPreferredSize(new Dimension(400, 250));
this.editor.setFont(this.font);
// Activate undo/redo features
this.undoRedoOperations();

this.editor.getDocument().addDocumentListener(new DocumentListener() {

private void updatelineCounter() {
Expand Down Expand Up @@ -81,6 +90,35 @@ public void removeUpdate(DocumentEvent arg0) {
});
}

private void undoRedoOperations(){
this.editor.getDocument().addUndoableEditListener(
new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent e) {
undoManager.addEdit(e.getEdit());
}
});
// Detect ctrl-z and ctrl-y to undo and redo
this.editor.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "undo");
this.editor.getActionMap().put("undo", new AbstractAction() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
undoManager.undo();
} catch (CannotUndoException ex) {
System.out.println("Unable to undo: " + ex);
}
}
});
this.editor.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "redo");
this.editor.getActionMap().put("redo", new AbstractAction() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
undoManager.redo();
} catch (CannotRedoException ex) {
System.out.println("Unable to redo: " + ex);
}
}
});
}
public String getContent() {
return this.editor.getText();
}
Expand Down

0 comments on commit ca2c728

Please sign in to comment.