Undo Function in Java

Closed
frustrated - Mar 12, 2017 at 08:17 AM
Ambucias
Posts
47363
Registration date
Monday February 1, 2010
Status
Moderator
Last seen
September 1, 2021
- Mar 12, 2017 at 04:57 PM
Hello, I am new to programmming and we are asked by our professor to make a simple virtual machine. So i am working with the ide and I am stuck in the undo and redo function. Here is my code. Can someone please help me?


package idevm;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.Document;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;


public class iCode extends javax.swing.JFrame {
private final JFileChooser openFileChooser;
public iCode() {
initComponents();
jTextArea3.setVisible(false);
Bok.setVisible(false);
openFileChooser = new JFileChooser();
openFileChooser.setCurrentDirectory(new File("c:\\Users"));
openFileChooser.setFileFilter( new FileNameExtensionFilter("Text file","txt"));
initialize();
}
private void initialize(){
this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("")));
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jButton4 = new javax.swing.JButton();
jMenuItem1 = new javax.swing.JMenuItem();
Bredo = new javax.swing.JButton();
Bundo = new javax.swing.JButton();
Brun = new javax.swing.JButton();
Bsave = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
jScrollPane3 = new javax.swing.JScrollPane();
jTextArea3 = new javax.swing.JTextArea();
Bok = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
MInew = new javax.swing.JMenuItem();
MIopen = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
MIsaveas = new javax.swing.JMenuItem();
MIexit = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jMenuItem6 = new javax.swing.JMenuItem();
jMenuItem7 = new javax.swing.JMenuItem();
jMenuItem8 = new javax.swing.JMenuItem();
jMenuItem9 = new javax.swing.JMenuItem();
jMenuItem10 = new javax.swing.JMenuItem();
Mabout = new javax.swing.JMenu();
jMenuItem5 = new javax.swing.JMenuItem();
Mcontents = new javax.swing.JMenu();
jMenuItem3 = new javax.swing.JMenuItem();
jMenuItem4 = new javax.swing.JMenuItem();

jButton4.setText("jButton4");

jMenuItem1.setText("jMenuItem1");

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setName("iCode"); // NOI18N

Bredo.setText("Redo");

Bundo.setText("Undo");

Brun.setText("Run");

Bsave.setText("Save");

jTextArea1.setBackground(new java.awt.Color(0, 0, 0));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Bookman Old Style", 0, 13)); // NOI18N
jTextArea1.setForeground(new java.awt.Color(153, 255, 255));
jTextArea1.setRows(5);
jTextArea1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jTextArea1.setSelectionColor(new java.awt.Color(204, 204, 204));
jScrollPane1.setViewportView(jTextArea1);

jTextArea2.setBackground(new java.awt.Color(102, 102, 102));
jTextArea2.setColumns(20);
jTextArea2.setFont(new java.awt.Font("Bookman Old Style", 0, 13)); // NOI18N
jTextArea2.setForeground(new java.awt.Color(153, 255, 255));
jTextArea2.setRows(5);
jTextArea2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jTextArea2.setSelectionColor(new java.awt.Color(204, 204, 204));
jScrollPane2.setViewportView(jTextArea2);

jTextArea3.setBackground(new java.awt.Color(102, 102, 102));
jTextArea3.setColumns(20);
jTextArea3.setFont(new java.awt.Font("Bookman Old Style", 0, 13)); // NOI18N
jTextArea3.setForeground(new java.awt.Color(153, 255, 255));
jTextArea3.setRows(5);
jTextArea3.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jTextArea3.setSelectionColor(new java.awt.Color(204, 204, 204));
jScrollPane3.setViewportView(jTextArea3);

Bok.setText("OK");

jMenuBar1.setBackground(new java.awt.Color(204, 204, 204));
jMenuBar1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jMenuBar1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jMenuBar1.setName("iCode"); // NOI18N

jMenu1.setText("File");

MInew.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
MInew.setText("New File");
MInew.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MInewActionPerformed(evt);
}
});
jMenu1.add(MInew);

MIopen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
MIopen.setText("Open File..");
MIopen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MIopenActionPerformed(evt);
}
});
jMenu1.add(MIopen);

jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem2.setText("Save");
jMenu1.add(jMenuItem2);

MIsaveas.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK));
MIsaveas.setText("Save As...");
MIsaveas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MIsaveasActionPerformed(evt);
}
});
jMenu1.add(MIsaveas);

MIexit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0));
MIexit.setText("Exit");
MIexit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MIexitActionPerformed(evt);
}
});
jMenu1.add(MIexit);

jMenuBar1.add(jMenu1);

jMenu2.setText("Edit");

jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem6.setText("Undo");
jMenu2.add(jMenuItem6);

jMenuItem7.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK));
jMenuItem7.setText("Redo");
jMenuItem7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem7ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem7);

jMenuItem8.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem8.setText("Cut");
jMenu2.add(jMenuItem8);

jMenuItem9.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem9.setText("Copy");
jMenuItem9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem9ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem9);

jMenuItem10.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem10.setText("Paste");
jMenu2.add(jMenuItem10);

jMenuBar1.add(jMenu2);

Mabout.setText("Run");

jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem5.setText("Run Project");
Mabout.add(jMenuItem5);

jMenuBar1.add(Mabout);

Mcontents.setText("Help");

jMenuItem3.setText("About");
Mcontents.add(jMenuItem3);

jMenuItem4.setText("Help");
Mcontents.add(jMenuItem4);

jMenuBar1.add(Mcontents);

setJMenuBar(jMenuBar1);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(Bundo, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE)
.addComponent(Bredo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Brun, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Bsave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 497, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Bok)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(Bredo, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Bundo, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Brun, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Bsave, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 447, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(Bok, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

private void MIexitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}

private void MInewActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("Text File", "txt");
JFileChooser saveAsFileChooser = new JFileChooser();
saveAsFileChooser.setApproveButtonText("Save");
saveAsFileChooser.setFileFilter(extensionFilter);
int actionDialog = saveAsFileChooser.showOpenDialog(this);
if (actionDialog != JFileChooser.APPROVE_OPTION) {
return;
}
// !! File fileName = new File(SaveAs.getSelectedFile() + ".txt");
File file = saveAsFileChooser.getSelectedFile();
if (!file.getName().endsWith(".txt")) {
file = new File(file.getAbsolutePath() + ".txt");
}
BufferedWriter outFile = null;
try {
outFile = new BufferedWriter(new FileWriter(file));

jTextArea1.write(outFile);

} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (outFile != null) {
try {
outFile.close();
} catch (IOException e) {}
}
}

}

private void MIopenActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser chooser=new JFileChooser();
chooser.showOpenDialog(null);
File f=chooser.getSelectedFile();
String filename=f.getAbsolutePath();
try{
FileReader reader=new FileReader(filename);
BufferedReader br=new BufferedReader(reader);
jTextArea1.read(br,null);
br.close();
jTextArea1.requestFocus();
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}

private void MIsaveasActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("Text File", "txt");
JFileChooser saveAsFileChooser = new JFileChooser();
saveAsFileChooser.setApproveButtonText("Save");
saveAsFileChooser.setFileFilter(extensionFilter);
int actionDialog = saveAsFileChooser.showOpenDialog(this);
if (actionDialog != JFileChooser.APPROVE_OPTION) {
return;
}
// !! File fileName = new File(SaveAs.getSelectedFile() + ".txt");
File file = saveAsFileChooser.getSelectedFile();
if (!file.getName().endsWith(".txt")) {
file = new File(file.getAbsolutePath() + ".txt");
}
BufferedWriter outFile = null;
try {
outFile = new BufferedWriter(new FileWriter(file));

jTextArea1.write(outFile);

} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (outFile != null) {
try {
outFile.close();
} catch (IOException e) {}
}
}
}

private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:

JTextArea txtArea = new JTextArea();
final UndoManager undo = new UndoManager(); //instantiate an UndoManager
Document doc = txtArea.getDocument();

doc.addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent evt) {
undo.addEdit(evt.getEdit());
}
});

txtArea.getActionMap().put("Undo", new AbstractAction("Undo") {
public void actionPerformed(ActionEvent evt) {
try {
if (undo.canUndo()) {
undo.undo();
}
} catch (CannotUndoException e) {
}
}
});

txtArea.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");



}

private void jMenuItem9ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
final Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
/**
  • @param args the command line arguments
  • /

public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  • For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  • /

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(iCode.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(iCode.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(iCode.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(iCode.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new iCode().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JButton Bok;
private javax.swing.JButton Bredo;
private javax.swing.JButton Brun;
private javax.swing.JButton Bsave;
private javax.swing.JButton Bundo;
private javax.swing.JMenuItem MIexit;
private javax.swing.JMenuItem MInew;
private javax.swing.JMenuItem MIopen;
private javax.swing.JMenuItem MIsaveas;
private javax.swing.JMenu Mabout;
private javax.swing.JMenu Mcontents;
private javax.swing.JButton jButton4;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem10;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JMenuItem jMenuItem6;
private javax.swing.JMenuItem jMenuItem7;
private javax.swing.JMenuItem jMenuItem8;
private javax.swing.JMenuItem jMenuItem9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextArea jTextArea2;
private javax.swing.JTextArea jTextArea3;
// End of variables declaration
}

1 reply

Ambucias
Posts
47363
Registration date
Monday February 1, 2010
Status
Moderator
Last seen
September 1, 2021
11,280
Mar 12, 2017 at 04:57 PM
Sorry but CCM does not provide help with homework, you must earn your own grades.
0