TITLE:JTextFieldでのBeep音の設定を変更する
#navi(../)
#tags(JTextField, Beep, ActionMap, DocumentFilter)
RIGHT:Posted by &author(aterai); at 2012-10-01
* JTextFieldでのBeep音の設定を変更する [#y6fbffa9]
`JTextField`などで、KBD{Delete}、KBD{Back Space}キーを押した時に鳴らす`Beep`音の設定を変更します。

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

** サンプルコード [#j457740c]
#code(link){{
String key = "delete-previous";
final Action deletePreviousAction = am.get(key);
am.put(key, new TextAction(DefaultEditorKit.deletePrevCharAction) {
  //@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 = "delete-next";
final Action deleteNextAction = am.get(key);
am.put(key, new TextAction(DefaultEditorKit.deleteNextCharAction) {
  //@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);
  }
});
}}

** 解説 [#j7ac5e77]
上記のサンプルでは、以下の二点を変更して、`Beep`音の設定を変更しています。

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

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

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