• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JTextFieldでのBeep音の設定を変更する
#navi(../)
RIGHT:Posted by [[aterai]] at 2012-10-01
*JTextFieldでのBeep音の設定を変更する [#y6fbffa9]
JTextFieldなどで、DELETE、BACK_SPACEキーを押した時に鳴らすBeep音の設定を変更します。

-&jnlp;
-&jar;
-&zip;

//#screenshot
#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())) {
    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())) {
    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()==0 || doc.getLength()==dot)) {
      if(dot==mark && doc.getLength()==0 || doc.getLength()==dot) {
        return;
      }
    }
    deleteNextAction.actionPerformed(e);
  }
});
}}

**解説 [#j7ac5e77]
上記のサンプルでは、以下の二点を変更して、Beep音の設定を変更しています。
- TextAction(DefaultEditorKit.deleteNextCharAction)#actionPerformed(ActionEvent) などをオーバーライドして、DELETEキーや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