2

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?

WearFox
  • 293
  • 2
  • 19

2 Answers2

2

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();
    }        
  }
});
Community
  • 1
  • 1
PeterK
  • 1,697
  • 10
  • 20
  • it doesn't work this is what i put in my code: Action action; action = getActionMap().get(DefaultEditorKit.beepAction); action.setEnabled(false); – WearFox Oct 09 '14 at 16:36
  • thanks for the update, I have added another suggestion you could try for stopping the beep. – PeterK Oct 09 '14 at 16:49
1

You can override the beep method from the Toolkit class:

public class MuteToolkit extends Toolkit {
    public void beep() {
        //do nothing
    }
    // [...] other methods
}

Then, set this class as the default toolkit:

System.setProperty("awt.toolkit", "package.MuteToolkit");

But may be not the best option, considering it disables all beeps.

elias
  • 15,010
  • 4
  • 40
  • 65
  • if I do that... I have to make a implementation of all methods and each one throw new UnsupportedOperationException, so in this method "public Image createImage(ImageProducer producer)" i can't left in blank – WearFox Oct 09 '14 at 16:29
  • You can also extends the basic implementation of Toolkit, the same returned from `getDefaultToolkit` method. – elias Oct 09 '14 at 16:35
  • I cant because these methods are protected... protected abstract DesktopPeer createDesktopPeer(Desktop target) throws HeadlessException; so DefaultToolkit don't have any of these – WearFox Oct 09 '14 at 16:47