I have a Java Swing application with a JTable, and I would like to add "undo" functionality to text editing in the first column of the table. After Googling and searching these forums for several hours, I have a very vague idea of how Undo works.
What I have put together so far is a customized JTextField class ( that compiles! ) with an UndoManager connected to the document part of the JTextField. I have then set the JTextField subclass as the default cell editor for that 1st column, and the code compiles fine. Now I wish to enable the user to undo edits in the currently selected table cell by using the JMenuItem "undo" to tell the undo manager to undo changes.
Here is where I add the class to the table as default cell editor:
ExclusionsTable.getColumnModel().getColumn(0).setCellEditor(new MyTableCellEditor() );
And below is the MyTableCellEditor() class:
/*
* MyTableCellEditor.java
*
* Created on November 30, 2006, 11:42 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package configurationeditor;
import java.awt.Component;
import javax.swing.AbstractCellEditor;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;
import javax.swing.text.Document;
import javax.swing.undo.UndoManager;
/**
*
* @author John.Gooch
*/
public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
// This is the component that will handle the editing of the cell value
private JComponent component = new JTextField();
protected UndoManager manager;
public MyTableCellEditor() {
super();
manager = new UndoManager();
Document document = ( (JTextField ) component ).getDocument();
//document.addUndoableEditListener( manager );
document.addUndoableEditListener( manager );
}
// This method is called when a cell value is edited by the user.
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int rowIndex, int vColIndex) {
// 'value' is value contained in the cell located at (rowIndex, vColIndex)
if (isSelected) {
// cell (and perhaps other cells) are selected
}
// Configure the component with the specified value
((JTextField)component).setText((String)value);
// Return the configured component
return component;
}
// This method is called when editing is completed.
// It must return the new value to be stored in the cell.
public Object getCellEditorValue() {
return ((JTextField)component).getText();
}
}
No problems with compiling, but how would I activate the undo function of the Undo manager? Here is my placeholder Undo function:
private void EditCutActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
Thank You for any advice or guidance,
John Gooch