2012-02-21 57 views
2

一個字符串我有一個的DocumentListener尋找JTextField中的任何改變:不斷閱讀從JTextField中

public class MyDocumentListener implements DocumentListener { 

    static String text; 

    public void insertUpdate(DocumentEvent e) { 
     updateLog(e); 
    } 
    public void removeUpdate(DocumentEvent e) { 
     updateLog(e); 
    } 
    public void changedUpdate(DocumentEvent e) { 
     //Plain text components do not fire these events 
    } 

    public static String passText() { 
     System.out.println("string that will be passed is: "+text); 
     return text; 
    } 

    public void updateLog(DocumentEvent e) { 

     Document doc = (Document)e.getDocument(); 
     int length = e.getLength(); 

     try { 
      text = doc.getText(0, length); 
     } catch (BadLocationException e1) { 
      e1.printStackTrace(); 
     } 
     System.out.println("you typed "+text); 
    } 
} 

,然後在其他類:

String info = MyDocumentListener.passText(); 

的問題是我只有一個字符,而不是整個字符串。有什麼建議麼?

+0

很簡單的;) – Hurdler 2012-02-21 19:00:43

回答

3

你得到變化的長度,而不是文件的長度:

int length = e.getLength(); // probably 1 

應該

int length = doc.getLength(); 
+0

我能說什麼......謝謝;) – Hurdler 2012-02-21 18:59:50

0

paislee提供的答案確實是正確的。你想添加另一種方式來做同樣的事情。您可以使用綁定,它添加了ValueHolders的概念,這些變量將存儲和反映imediatley圖形組件的任何屬性更改。它可以提供一種非常有效的方式來使用Swing實現MVC設計模式,因爲Model-Controller-View之間的通信更加情感化和解耦。

JGoodies擁有優秀的開源實現。如果您可以花一些時間想要改進設計,請不要猶豫,看一看。