Swing/UndoManager のバックアップ差分(No.14)
- バックアップ一覧
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- バックアップ を表示
- Swing/UndoManager へ行く。
- 1 (2009-06-15 (月) 13:35:15)
- 2 (2010-05-11 (火) 20:53:16)
- 3 (2011-05-11 (水) 19:03:05)
- 4 (2012-10-15 (月) 19:54:41)
- 5 (2013-01-09 (水) 20:48:48)
- 6 (2013-07-26 (金) 01:22:10)
- 7 (2013-11-01 (金) 16:41:05)
- 8 (2014-11-26 (水) 18:15:00)
- 9 (2015-01-27 (火) 17:00:38)
- 10 (2015-04-07 (火) 20:12:28)
- 11 (2017-02-24 (金) 19:07:58)
- 12 (2017-04-04 (火) 14:17:08)
- 13 (2017-12-29 (金) 16:22:53)
- 14 (2019-12-12 (木) 15:20:30)
- 15 (2021-06-12 (土) 15:38:48)
- 追加された行はこの色です。
- 削除された行はこの色です。
---
category: swing
folder: UndoManager
title: UndoManagerでJTextFieldのUndo、Redoを行う
tags: [JTextField, JTextComponent, UndoManager, ActionMap, Document]
author: aterai
pubdate: 2009-06-15T13:35:15+09:00
description: JTextFieldのドキュメントにUndoManagerを追加して、Undo、Redoを行います。
image: https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTWX1uwgqI/AAAAAAAAApI/zvwc9TUlj4E/s800/UndoManager.png
---
* 概要 [#summary]
`JTextField`のドキュメントに`UndoManager`を追加して、`Undo`、`Redo`を行います。
#download(https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTWX1uwgqI/AAAAAAAAApI/zvwc9TUlj4E/s800/UndoManager.png)
* サンプルコード [#sourcecode]
#code(link){{
private static void initUndoRedo(JTextComponent tc) {
UndoManager manager = new UndoManager();
tc.getDocument().addUndoableEditListener(manager);
tc.getActionMap().put("undo", new UndoAction(manager));
tc.getActionMap().put("redo", new RedoAction(manager));
InputMap imap = tc.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
imap.put(KeyStroke.getKeyStroke(
KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "undo");
imap.put(KeyStroke.getKeyStroke(
KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "redo");
}
private static class UndoAction extends AbstractAction {
private final UndoManager undoManager;
public UndoAction(UndoManager manager) {
super("undo");
this.undoManager = manager;
}
@Override public void actionPerformed(ActionEvent e) {
try {
undoManager.undo();
} catch (CannotUndoException cue) {
//cue.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
}
}
}}
* 解説 [#explanation]
`Document#addUndoableEditListener(UndoManager)`メソッドを使用して`JTextField`に`UndoManager`を追加し、以下のキー入力で`Undo`、`Redo`が実行できるように設定しています。
- `Undo` : KBD{Ctrl+Z}
- `Redo` : KBD{Ctrl+Y}
* 参考リンク [#reference]
- [https://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#undo Implementing Undo and Redo (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/undo/UndoManager.html UndoManager (Java Platform SE 8)]
- [[UndoManagerを使用した文字列選択ペーストの動作を変更する>Swing/ReplaceUndoableEdit]]
* コメント [#comment]
#comment
#comment