Search code examples
javajtextfieldjtextpanetoolkit

How to remove the sound played when focus is transferred to an uneditable JTextComponent


How can I get rid of the sound when I give focus to an uneditable JTextField or JTextPane?

Whenever I transfer focus to a JTextPane which is uneditable and hit Enter, a sound plays which is equals to the "beep" of the Toolkit class:

Toolkit.getDefaultToolkit.beet();

How can I make it play no sound?


Solution

  • You might be able to try the idea from this question, quoted:

    The idea is to get the beep action for the text field and disabling it.

    JTextField field = new JTextField();
    Action action;
    action = field.getActionMap().get(DefaultEditorKit.beepAction);
    action.setEnabled(false);
    

    If that does not work, you can try to add a KeyListener, that would consume the KeyEvent that causes the beep.

    JTextField textField = new JTextField();
    textField.addKeyListener(new KeyAdapter() {
      @Override
      public void keyTyped(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_ENTER){
          // will consume the event and stop it from processing normally
          e.consume();
        }        
      }
    });