Disable beep when backspace is pressed in an empty JTextField

浪子不回头ぞ 提交于 2019-12-02 08:44:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!