好吧,我正在开发一个需要用户输入的 java 项目。我意识到如果用户在字段中没有字符时按退格键,则会听到窗口警告声。请问我怎么能阻止这个。如果在不同平台上的行为可能完全不同,我的系统是 Windows 10。谢谢你。
问问题
201 次
1 回答
3
不同平台上的行为可能会有所不同。
是的,行为可能会有所不同,因为它是由 LAF 控制的,所以你不应该真的改变它。
但是要了解 Swing 是如何工作的,您需要了解 Swing 使用Action
提供的一个DefaultEditorKit
来提供文本组件的编辑功能。
以下是当前“删除前一个字符”操作的代码(取自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);
}
}
}
如果您不喜欢哔声,那么您需要创建自己的自定义操作来消除哔声。(即不提供错误反馈)。自定义 Action 后,您可以使用以下方法更改单个文本字段:
textField.getActionMap().put(DefaultEditorKit.deletePrevCharAction, new MyDeletePrevCharAction());
或者您可以使用以下方法更改所有文本字段:
ActionMap am = (ActionMap)UIManager.get("TextField.actionMap");
am.put(DefaultEditorKit.deletePrevCharAction, new MyDeletePrevCharAction());
于 2016-11-06T14:47:40.610 回答