如何为JTextArea实现撤消和重做

时间:2015-01-27 06:37:46

标签: java swing jtextarea undo-redo

我已经基于JTextArea开发了基于Swing的应用程序。我向我的应用程序添加了撤消和重做选项。我有三个菜单项,打开,回滚和重做。我的问题是当我打开多个空文档并写一些打开Documents上的文本。当我点击Rollback时,所有打开的文档的内容都被删除/回滚,不仅要关注Document.Please检查它。谢谢。 我的代码:

    public class UndoAndRedo extends javax.swing.JFrame {
    int i = 0;
    JTextArea textArea;
    JScrollPane scrollPane;
    int tabCount=0;
    UndoManager undoManager = new UndoManager();
    public UndoAndRedo() {
        initComponents();
    }
    @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        tp = new javax.swing.JTabbedPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        open = new javax.swing.JMenuItem();
        rollback = new javax.swing.JMenuItem();
        redo = new javax.swing.JMenuItem();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        fileMenu.setText("File");
        open.setText("Open");
        open.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openActionPerformed(evt);
            }
        });
        fileMenu.add(open);
        rollback.setText("Rollback");
        rollback.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rollbackActionPerformed(evt);
            }
        });
        fileMenu.add(rollback);
        redo.setText("Redo");
        redo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                redoActionPerformed(evt);
            }
        });
        fileMenu.add(redo);
        jMenuBar1.add(fileMenu);
        setJMenuBar(jMenuBar1);
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
        );
        pack();
    }                     
    private void openActionPerformed(java.awt.event.ActionEvent evt) {
    textArea=new JTextArea();
    textArea.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
    textArea.setDocument(new CustomUndoPlainDocument());
    scrollPane=new JScrollPane(textArea);
    tabCount++;
    tp.addTab("Document "+tabCount, null, scrollPane, "Document "+tabCount);
    try {
        tp.setSelectedIndex(tabCount-1);
    }
    catch(IndexOutOfBoundsException i) {  
    }
    textArea.requestFocus();
    textArea.setCaretPosition(0);
    textArea.getDocument().addUndoableEditListener(undoManager);
    }
    private void rollbackActionPerformed(java.awt.event.ActionEvent evt) {
        if (undoManager.canUndo()) {
            undoManager.undo();
        }
    }
    private void redoActionPerformed(java.awt.event.ActionEvent evt) {
        if (undoManager.canRedo()) {
            undoManager.redo();
        }
    }
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(UndoAndRedo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(UndoAndRedo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(UndoAndRedo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(UndoAndRedo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new UndoAndRedo().setVisible(true);
            }
        });
    }
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem open;
    private javax.swing.JMenuItem redo;
    private javax.swing.JMenuItem rollback;
    private javax.swing.JTabbedPane tp;

    class CustomUndoPlainDocument extends PlainDocument {
        private CompoundEdit compoundEdit;
        @Override protected void fireUndoableEditUpdate(UndoableEditEvent e) {
        if (compoundEdit == null) {
            super.fireUndoableEditUpdate(e);
        } else {
            compoundEdit.addEdit(e.getEdit());
            }
        }
        @Override public void replace(
            int offset, int length,
            String text, AttributeSet attrs) throws BadLocationException {
            if (length == 0) {
                super.replace(offset, length, text, attrs);
            } else {
                compoundEdit = new CompoundEdit();
                super.fireUndoableEditUpdate(new UndoableEditEvent(this, compoundEdit));
                super.replace(offset, length, text, attrs);
                compoundEdit.end();
                compoundEdit = null;
            }
        }
    } 
}

0 个答案:

没有答案