检测退格键按下

时间:2015-06-19 16:37:50

标签: java filter document

有没有办法使用文档过滤器检测键盘上的退格键何时被按下? The following is an edited code extract from here

例如

public class IntFilter extends DocumentFilter {
    boolean trueFalse = true;
    public void insertString(DocumentFilter.FilterBypass fb, int offset,
                             String string, AttributeSet attr)
            throws BadLocationException {

        StringBuffer buffer = new StringBuffer(string);
        for (int i = buffer.length() - 1; i >= 0; i--) {
            char ch = buffer.charAt(i);
            if (!Character.isDigit(ch)) {
                buffer.deleteCharAt(i);
                trueFalse = false;
            }
            /*
            else if (backspace pressed)
            {
                trueFalse = true;
            }
            */
            else{
                trueFalse = true;
            }
        }
        super.insertString(fb, offset, buffer.toString(), attr);
    }

    public void replace(DocumentFilter.FilterBypass fb,
                        int offset, int length, String string, AttributeSet attr) throws BadLocationException {
        if (length > 0) fb.remove(offset, length);
        insertString(fb, offset, string, attr);
    }
}

2 个答案:

答案 0 :(得分:0)

按退格键不会触发insertString()方法。它应该触发remove()方法(仅当文本被实际删除时,例如,当插入符号位于文本的开头时不是这种情况)。

但您可以使用KeyListenerdoc)检测任何击键。以下是检测退格键的方法:

public class KeyEventDemo implements KeyListener {

    /** Handle the key typed event from the text field. */
    public void keyTyped(KeyEvent e) {}

    /** Handle the key-pressed event from the text field. */
    public void keyPressed(KeyEvent e) {}

    /** Handle the key-released event from the text field. */
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode()==KeyEvent.VK_BACK_SPACE){
             // Do something...
        }
    }

}

答案 1 :(得分:0)

据我所知,在DocumentFilter中无法检测到它。

如果选择一个字符并按DEL键,则按BACKSPACE键。已删除文本的偏移量和长度相同。

相反,您可以为BACKSPACE处理定义KeyBinding并将代码放在那里。