问题
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.
回答1:
This code worked for me.
Action beep = textArea.getActionMap().get(DefaultEditorKit.deletePrevCharAction);
beep.setEnabled(false);
回答2:
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);
回答3:
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.
来源:https://stackoverflow.com/questions/13427174/disable-beep-when-backspace-is-pressed-in-an-empty-jtextfield