清空jtextfield/jpassword删除声音

Empty jtextfield/jpassword delete sound

嗯,我正在做一个需要用户输入的 java 项目。我意识到如果用户在字段中没有字符时按退格键,则会听到 window 警告声音。请问我怎样才能阻止这个。我的系统是 windows 10 if at all the behavior may be different on different platforms.谢谢。

behavior may be different on different platforms.

是的,行为可能会有所不同,因为它是由 LAF 控制的,所以您不应该真的改变它。

但要了解 Swing 的工作原理,您需要了解 Swing 使用 DefaultEditorKit 提供的 Action 来提供文本组件的编辑功能。

以下是当前 "delete previous character" 操作的代码(取自 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());