user1282716
user1282716

Reputation:

Disable beep when backspace is pressed in an empty JTextField

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.

Upvotes: 2

Views: 2699

Answers (4)

Termenoil
Termenoil

Reputation: 31

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.getSelectionEnd() > 0)
            action.actionPerformed(e);
        
    }
    
}

Upvotes: 0

Daniel Hladík
Daniel Hladík

Reputation: 31

This code worked for me.

Action beep = textArea.getActionMap().get(DefaultEditorKit.deletePrevCharAction);
beep.setEnabled(false);

Upvotes: 3

austin
austin

Reputation: 5866

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.

Upvotes: 0

austin
austin

Reputation: 5866

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);

Upvotes: 0

Related Questions