2014-03-01 88 views
0

當我嘗試追加一個字符或字符串jtextarea後按特定按鈕,奇怪的事情發生,例如我想附加'}'按「{」通過用戶在JTextArea中,通過下面的代碼,在JTextArea中最後一個字符串將是「} {」的而不是「{}」使用KeyEvent(KeyPressed,KeyTyped,...)附加一個字符到JTextArea

private void keyPressedEvent(java.awt.event.KeyEvent evt) 
{ 
    if(evt.getkeychar() == '{') 
    { 
     JtextArea1.append("}"); 
    } 
} 

回答

4

你應該幾乎從不使用KeyListener的上一個JTextArea後或其他JTextComponent。爲此,我會使用一個DocumentFilter,它允許您在用戶輸入發送給Document之前更新Document。

例如,

import javax.swing.*; 
import javax.swing.text.*; 

public class DocFilterEg { 
    public static void main(String[] args) { 
     JTextArea textArea = new JTextArea(10, 20); 
     PlainDocument doc = (PlainDocument) textArea.getDocument(); 
     doc.setDocumentFilter(new DocumentFilter() { 
     @Override 
     public void insertString(FilterBypass fb, int offset, String text, 
       AttributeSet attr) throws BadLocationException { 
      text = checkTextForParenthesis(text); 
      super.insertString(fb, offset, text, attr); 
     } 

     @Override 
     public void replace(FilterBypass fb, int offset, int length, 
       String text, AttributeSet attrs) throws BadLocationException { 
      text = checkTextForParenthesis(text); 
      super.replace(fb, offset, length, text, attrs); 
     } 

     private String checkTextForParenthesis(String text) { 
      if (text.contains("{") && !text.contains("}")) { 
       int index = text.indexOf("{") + 1; 
       text = text.substring(0, index) + "}" + text.substring(index); 
      } 
      return text; 
     } 
     }); 
     JOptionPane.showMessageDialog(null, new JScrollPane(textArea)); 
    } 
} 
+0

所以沒有任何辦法做我必須通過KeyPreesed或任何其他的KeyListener之前說的嗎? – user3369353

+0

@ user3369353:它可以完成,但不建議您使用這樣的低級偵聽器。 –

+0

可以發表在這種情況下使用Documentfilter的示例代碼? – user3369353