2015-06-19 65 views
0

有没有办法检测键盘上的退格键何时被按下,使用文档过滤器? 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); 
    } 
} 
+0

使用文档过滤器是绝对必要的吗? – nom

+0

@NabeelOmer对于这个问题是的。在实际的程序中,我正在试验一个DocumentListener – Dan

回答

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... 
     } 
    } 

} 
+0

你会怎么做,所以退格键触发remove()?当我试图添加它时,每次按任何键时都会调用它,而不仅仅是退格键。 – Dan

+0

当任何*键被按下时'remove()'被调用?如果是这样,可能有错误。删除文本时会调用remove(),当您按下退格键或* Suppr *时,或者在选择某个文本(首先删除文本,然后插入新文本)时按任意键时可能会发生这种情况。 –

0

据我所知在DocumentFilter中没有办法检测到。

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

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

+0

而在这个例子中,你有什么建议我添加键绑定? – Dan