2015-06-19 66 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