Swing/DefaultEditorKit のバックアップの現在との差分(No.22)
- category: swing folder: DefaultEditorKit title: DefaultEditorKitでポップアップメニューからコピー tags: [DefaultEditorKit, JTextField, JTextComponent, JPopupMenu] author: aterai pubdate: 2005-07-25T08:41:31+09:00 description: DefaultEditorKitを使って、JTextFieldなどでポップアップメニューを使ったコピー、貼り付け、切り取りを行います。 image:
概要
DefaultEditorKit
を使って、JTextField
などでポップアップメニューを使ったコピー、貼り付け、切り取りを行います。
Screenshot
Advertisement
サンプルコード
#spandel
//textField.setComponentPopupMenu(new TextFieldPopupMenu());
#spanend
#spanadd
// textField.setComponentPopupMenu(new TextFieldPopupMenu());
#spanend
class TextFieldPopupMenu extends JPopupMenu {
private final Action cutAction = new DefaultEditorKit.CutAction();
private final Action copyAction = new DefaultEditorKit.CopyAction();
private final Action pasteAction = new DefaultEditorKit.PasteAction();
private final Action deleteAction = new AbstractAction("delete") {
@Override public void actionPerformed(ActionEvent e) {
Component c = getInvoker();
if (c instanceof JTextComponent) {
((JTextComponent) c).replaceSelection(null);
}
}
};
private final Action cut2Action = new AbstractAction("cut2") {
@Override public void actionPerformed(ActionEvent e) {
Component c = getInvoker();
if (c instanceof JTextComponent) {
((JTextComponent) c).cut();
}
}
};
#spanadd
#spanend
protected TextFieldPopupMenu() {
super();
add(cutAction);
add(copyAction);
add(pasteAction);
add(deleteAction);
addSeparator();
add(cut2Action);
}
#spanadd
#spanend
@Override public void show(Component c, int x, int y) {
if (c instanceof JTextComponent) {
JTextComponent tc = (JTextComponent) c;
boolean f = tc.getSelectionStart() != tc.getSelectionEnd();
cutAction.setEnabled(f);
copyAction.setEnabled(f);
deleteAction.setEnabled(f);
cut2Action.setEnabled(f);
super.show(c, x, y);
}
}
}
View in GitHub: Java, Kotlin解説
上記のサンプルでは、DefaultEditorKit.CopyAction
をポップアップメニューに追加してクリップボードを使ったコピーなどを可能にしています。
-
DefaultEditorKit.CopyAction
をポップアップメニューに追加してクリップボードを使ったコピーなどが可能になるよう設定- サンプルの
cut2
のように、JTextComponent#cut()
メソッドなどを使用する方法もある
- サンプルの
- サンプルの
cut2
のように、JTextComponent#cut()
メソッドなどを使用する方法もある
サンプルを
Java Web Start
で起動した場合は、システム全体の共有クリップボードにはアクセス不可能で、アプリケーション内部のみでのコピー、貼り付けとなります。
- サンプルを
Java Web Start
で起動した場合は、システム全体の共有クリップボードにはアクセス不可能でアプリケーション内部のみでのコピー、貼り付けとなる - ClipboardServiceでシステム全体の共有クリップボードにアクセスする