---
category: swing
folder: DeleteKeyBeep
title: JTextFieldでのBeep音の設定を変更する
tags: [JTextField, Beep, ActionMap, DocumentFilter]
tags: [JTextField, Sound, ActionMap, DocumentFilter]
author: aterai
pubdate: 2012-10-01T14:42:41+09:00
description: JTextFieldなどで、KBD{Delete}、KBD{Back Space}キーを押した時に鳴らすBeep音の設定を変更します。
image: https://lh6.googleusercontent.com/-zIUmkF2C9FA/UGkqdcWDLVI/AAAAAAAABTk/F4nun0GDLZc/s800/DeleteKeyBeep.png
---
* 概要 [#summary]
`JTextField`などで、KBD{Delete}、KBD{Back Space}キーを押した時に鳴らす`Beep`音の設定を変更します。

#download(https://lh6.googleusercontent.com/-zIUmkF2C9FA/UGkqdcWDLVI/AAAAAAAABTk/F4nun0GDLZc/s800/DeleteKeyBeep.png)

* サンプルコード [#sourcecode]
#code(link){{
String key = DefaultEditorKit.deletePrevCharAction; // delete-previous
Action deletePreviousAction = am.get(key);
am.put(key, new TextAction(key) {
  // @see javax/swing/text/DefaultEditorKit.java DeletePrevCharAction
  @Override public void actionPerformed(ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    if (target != null && target.isEditable()) {
      Caret caret = target.getCaret();
      int dot = caret.getDot();
      int mark = caret.getMark();
      if (dot == 0 && mark == 0) {
        return;
      }
    }
    deletePreviousAction.actionPerformed(e);
  }
});
key = DefaultEditorKit.deleteNextCharAction; // delete-next
Action deleteNextAction = am.get(key);
am.put(key, new TextAction(key) {
  // @see javax/swing/text/DefaultEditorKit.java DeleteNextCharAction
  @Override public void actionPerformed(ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    if (target != null && target.isEditable()) {
      Document doc = target.getDocument();
      Caret caret = target.getCaret();
      int dot = caret.getDot();
      int mark = caret.getMark();
      if (dot == mark && doc.getLength() == dot) {
        return;
      }
    }
    deleteNextAction.actionPerformed(e);
  }
});
}}

* 解説 [#explanation]
上記のサンプルでは、`JTextField`の`Beep`音の設定を以下`2`点変更して動作テストを行っています。

- `TextAction(DefaultEditorKit.deleteNextCharAction)#actionPerformed(ActionEvent)`メソッドなどをオーバーライドしてKBD{Delete}キーやKBD{Back Space}キーで文字の削除がなくても`Beep`音を鳴らさないように変更したアクションを`ActionMap`に設定
- `5`文字以上入力できないように制限し、超える場合は`Beep`音を鳴らす`DocumentFilter`を作成して`AbstractDocument#setDocumentFilter(DocumentFilter)`で設定

* 参考リンク [#reference]
- [https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/uiswing/examples/components/TextComponentDemoProject/src/components/DocumentSizeFilter.java DocumentSizeFilter.java]
-- via: [https://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html Text Component Features (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)]

* コメント [#comment]
#comment
#comment