空jtextfield/jpassword删除声音
问题描述:
那么,我正在开发一个需要用户输入的java项目。我意识到,如果用户在字段中没有字符时按下退格键,则会听到窗口警告声。我怎样才能阻止这个请。如果在不同平台上的行为可能不同,我的系统是Windows 10。谢谢。空jtextfield/jpassword删除声音
答
行为在不同平台上可能会有所不同。
是的,行为可以是不同的,因为它是由LAF控制的,所以你不应该改变它。
但要理解Swing的工作原理,您需要了解Swing使用DefaultEditorKit
提供的Action
来提供文本组件的编辑功能。
以下为当前的“删除前一个字符”行动的代码(从DefaultEditKit
拍摄):
/*
* Deletes the character of content that precedes the
* current caret position.
* @see DefaultEditorKit#deletePrevCharAction
* @see DefaultEditorKit#getActions
*/
static class DeletePrevCharAction extends TextAction {
/**
* Creates this object with the appropriate identifier.
*/
DeletePrevCharAction() {
super(DefaultEditorKit.deletePrevCharAction);
}
/**
* The operation to perform when this action is triggered.
*
* @param e the action event
*/
public void actionPerformed(ActionEvent e) {
JTextComponent target = getTextComponent(e);
boolean beep = true;
if ((target != null) && (target.isEditable())) {
try {
Document doc = target.getDocument();
Caret caret = target.getCaret();
int dot = caret.getDot();
int mark = caret.getMark();
if (dot != mark) {
doc.remove(Math.min(dot, mark), Math.abs(dot - mark));
beep = false;
} else if (dot > 0) {
int delChars = 1;
if (dot > 1) {
String dotChars = doc.getText(dot - 2, 2);
char c0 = dotChars.charAt(0);
char c1 = dotChars.charAt(1);
if (c0 >= '\uD800' && c0 <= '\uDBFF' &&
c1 >= '\uDC00' && c1 <= '\uDFFF') {
delChars = 2;
}
}
doc.remove(dot - delChars, delChars);
beep = false;
}
} catch (BadLocationException bl) {
}
}
if (beep) {
UIManager.getLookAndFeel().provideErrorFeedback(target);
}
}
}
如果你不喜欢的哔哔声,那么你就需要创建自己的自定义操作消除嘟嘟声。 (即不提供错误反馈)。一旦你自定义操作,您可以使用不是改变单一的文本字段:
textField.getActionMap().put(DefaultEditorKit.deletePrevCharAction, new MyDeletePrevCharAction());
,也可以使用更改所有文本字段:
ActionMap am = (ActionMap)UIManager.get("TextField.actionMap");
am.put(DefaultEditorKit.deletePrevCharAction, new MyDeletePrevCharAction());
感谢。这给了我足够的暗示来解决问题。非常感谢。 – user7121782
在答案解决你的问题,一定要接受它。访问[接受答案如何工作?](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)了解更多,并确保接受答案。谢谢! –