不同平台上的行为可能不同。
是的,行为可能会有所不同,因为它是由 LAF 控制的,所以你不应该真的改变它。
但要了解 Swing 的工作原理,您需要了解 Swing 使用 DefaultEditorKit 提供的 Action 来提供文本组件的编辑功能。
以下是当前“删除前一个字符”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);
}
}
}
如果您不喜欢哔声,那么您需要创建自己的自定义操作来消除哔声。 (即不提供错误反馈)。自定义 Action 后,您可以使用以下方法更改单个文本字段:
textField.getActionMap().put(DefaultEditorKit.deletePrevCharAction, new MyDeletePrevCharAction());
或者您可以使用以下方法更改所有文本字段:
ActionMap am = (ActionMap)UIManager.get("TextField.actionMap");
am.put(DefaultEditorKit.deletePrevCharAction, new MyDeletePrevCharAction());