1

I have Developed a Swing Based Application based on JTextArea.I Add Undo and Redo Options to My Application.I have Three Menu Items,Open,Rollback and Redo.My problem is when I open more than one Empty Documents and write some text on opened Documents.When I click on Rollback the contents of all opened Documents are removed/rollback not only focus Document.Please Check it.Thank you. My Code:

    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;
            }
        }
    } 
}
  • 2
    You'll likely need a `UndoManager` for individual `Document`...This means, when you use your menus, you will need to determine which `Document` is currently focused and retrieve it's `UndoManager`... – MadProgrammer Jan 27 '15 at 06:43
  • 2
    Possible duplicates: http://stackoverflow.com/questions/12030836/undo-functionality-in-jtextarea http://stackoverflow.com/questions/2547404/using-undo-and-redo-for-jtextarea?rq=1 – dramzy Jan 27 '15 at 06:44
  • Thank you for reply.How to determine the focused document and what code should I write after focusing.Please check it. – user3792689 Jan 27 '15 at 08:48
  • 2
    @user3792689: As shown [here](http://stackoverflow.com/q/720208/230513). – trashgod Jan 27 '15 at 09:39
  • You can also use [`KeyboardFocusManager#getFocusOwner`](http://docs.oracle.com/javase/7/docs/api/java/awt/KeyboardFocusManager.html#getFocusOwner()). You will need to determine if the return `Component` is a `JTextArea` or not first – MadProgrammer Jan 27 '15 at 23:06
  • Hi,Still I didn't get solution for this issue.Please check this,how to write the code for Focused JTextarea only Undo/Redo.Please give me some solution for this. – user3792689 Jan 30 '15 at 11:09

0 Answers0