我有一个 DocumentListener 来查找 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();
问题是我只得到一个字符,而不是整个字符串。有什么建议吗?
最佳答案
您获得的是更改的长度,而不是文档的长度:
int length = e.getLength(); // probably 1
应该是
int length = doc.getLength();
关于java - 不断从 JTextField 读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9383265/