Reputation:
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
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
Reputation: 31
This code worked for me.
Action beep = textArea.getActionMap().get(DefaultEditorKit.deletePrevCharAction);
beep.setEnabled(false);
Upvotes: 3
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
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