001package com.ganteater.ae.desktop.editor; 002 003import java.awt.event.KeyAdapter; 004import java.awt.event.KeyEvent; 005 006import javax.swing.JTextArea; 007import javax.swing.text.Document; 008import javax.swing.undo.UndoManager; 009 010import org.apache.commons.lang.StringUtils; 011 012public class TextEditor extends JTextArea { 013 014 private static final long serialVersionUID = -298735473495909314L; 015 private final UndoManager undo = new UndoManager(); 016 017 public TextEditor() { 018 super(); 019 setTabSize(4); 020 Document doc = getDocument(); 021 doc.addUndoableEditListener((evt) -> undo.addEdit(evt.getEdit())); 022 addKeyListener(new KeyAdapter() { 023 @Override 024 public void keyPressed(KeyEvent e) { 025 if (e.getKeyCode() == KeyEvent.VK_Z && e.isControlDown()) { 026 undo(); 027 } else if (e.getKeyCode() == KeyEvent.VK_Y && e.isControlDown()) { 028 redo(); 029 } 030 } 031 }); 032 033 } 034 035 public void redo() { 036 int caretPosition = getCaretPosition(); 037 if (undo.canRedo()) { 038 undo.redo(); 039 if (getDocument().getLength() == 0) { 040 if (undo.canRedo()) { 041 undo.redo(); 042 } else if (undo.canUndo()) { 043 undo.undo(); 044 } 045 } 046 } 047 setCaretPosition(caretPosition); 048 } 049 050 public void undo() { 051 int caretPosition = getCaretPosition(); 052 if (undo.canUndo()) { 053 undo.undo(); 054 if (getDocument().getLength() == 0) { 055 if (undo.canUndo()) { 056 undo.undo(); 057 } else if (undo.canRedo()) { 058 undo.redo(); 059 } 060 } 061 } 062 setCaretPosition(caretPosition); 063 } 064 065 public void removeLine() { 066 int caretPosition = getCaretPosition(); 067 String text = getText(); 068 int start = StringUtils.lastIndexOf(text, "\n", caretPosition - 1); 069 start = start < 0 ? 0 : start + 1; 070 int end = StringUtils.indexOf(text, "\n", caretPosition); 071 end = end < 0 ? text.length() - 1 : end + 1; 072 start = start < end ? start : end; 073 replaceRange("", start, end); 074 setCaretPosition(start == 0 ? 0 : start); 075 } 076 077 public void setOriginalText(String xmlText) { 078 setText(xmlText); 079 } 080 081}