Martedì, Agosto 18, 2009
Java swing: ‘undo’ e ‘redo’ in una JTextArea
Il seguente metodo statico prende una JTextArea e le aggiunge un UndoManager, in modo che si possano usare i tasti Ctrl-Z e Ctrl-Y per annullare e ripetere le modifiche rispettivamente (undo e redo).
/**
* Method adds the undo/redo (Ctrl-Z/Ctrl-Y) capabilities to given JTextArea.
* @param area JTextArea to modify.
*/
public static void addUndoRedo(JTextArea area){
final UndoManager undoman = new UndoManager();
// add listener
area.getDocument().addUndoableEditListener(new UndoableEditListener(){
public void undoableEditHappened(UndoableEditEvent evt){
undoman.addEdit(evt.getEdit());
}
});
//actions for the undo/redo commands
AbstractAction undo_action = new AbstractAction(){
public void actionPerformed(ActionEvent evt){
try{
if(undoman.canUndo()){
undoman.undo();
}
}
catch(CannotUndoException e){ e.printStackTrace(); }
}
};
AbstractAction redo_action = new AbstractAction(){
public void actionPerformed(ActionEvent evt){
try{
if(undoman.canRedo()){
undoman.redo();
}
}
catch(CannotRedoException e){ e.printStackTrace(); }
}
};
//create and bind the undo/redo actions
area.getActionMap().put("Undo", undo_action);
area.getActionMap().put("Redo", redo_action);
area.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
area.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
}
Aggiungi un commento
Completa la form sottostante per aggiungere un commento