2

Beginner here. Does anybody know a quick and easy way to get a JTextField to not beep when backspace is pressed and the field is empty? I've seen a couple things online about changing the DefaultEditorKit, but nothing I was able to make sense of. Any help would be greatly appreciated.

  • For others experiencing this problem, I answered this here: http://stackoverflow.com/a/30799707/396747 – Gary Jun 12 '15 at 09:31

4 Answers4

3

This code worked for me.

Action beep = textArea.getActionMap().get(DefaultEditorKit.deletePrevCharAction);
beep.setEnabled(false);
  • 1
    Unfortunately this code has the side effect of preventing all backspace delete operations. – Gary Jun 12 '15 at 09:07
  • But you can do: Action beep = textArea.getActionMap().get(DefaultEditorKit.deletePrevCharAction); textArea.getActionMap().put(DefaultEditorKit.deletePrevCharAction, new DelActionWrapper(textArea, beep)); where DelActionWrapper implements Action, and delegates calls to beep action except for actionPeform when textArea is empty. Maybe there is an easier way – Yevgen Yampolskiy Oct 23 '16 at 16:59
0

Edit: I put another answer later that probably is easier to do. I would read that one first.

You could try to override the JTextField's processKeyEvent method and check if 1.) the key pressed is the backspace key and 2.) the JTextField is empty. If either of those are false, then it should behave as normal. Otherwise, you can just return from the method.

austin
  • 5,816
  • 2
  • 32
  • 40
0

I haven't had a chance to try this out, but you might be able to disable the beep action.

JTextField field = new JTextField();
Action action;
a = field.getActionMap().get(DefaultEditorKit.beepAction);
a.setEnabled(false);
austin
  • 5,816
  • 2
  • 32
  • 40
0

This will remove the beep sound:

JTextField textField = new JTextField();
Action deleteAction = textField.getActionMap().get(DefaultEditorKit.deletePrevCharAction);
textField.getActionMap().put( DefaultEditorKit.deletePrevCharAction, new DeleteActionWrapper(textField, deleteAction) );
public class DeleteActionWrapper extends AbstractAction{
    
    private JTextField textField;
    private Action action;
    
    public DeleteActionWrapper(JTextField textField, Action action){
        
        this.textField = textField;
        this.action = action;
        
    }
    
    @Override
    public void actionPerformed(ActionEvent e){
        
        if(textField.getCaretPosition() > 0)
            action.actionPerformed(e);
        
    }
    
}
Termenoil
  • 21
  • 4