对JTextField或者JTextArea的Document添加addDocumentListener(DocumentListener listener),实现 void changedUpdate(DocumentEvent e) Gives notification that an attribute or set of attributes changed. void insertUpdate(DocumentEvent e) // 在这里取得字符串,每输入一个,这里就会执行一次. Gives notification that there was an insert into the document. void removeUpdate(DocumentEvent e) Gives notification that a portion of the document has been removed. 这样,就可以实时监听了.
void changedUpdate(DocumentEvent e)
Gives notification that an attribute or set of attributes changed.
void insertUpdate(DocumentEvent e) // 在这里取得字符串,每输入一个,这里就会执行一次.
Gives notification that there was an insert into the document.
void removeUpdate(DocumentEvent e)
Gives notification that a portion of the document has been removed.
这样,就可以实时监听了.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;public class WriteObject {public static void main(String[] args) {
JFrame frame = new JFrame("Text");JTextArea textArea = new JTextArea(30, 30);
textArea.setLineWrap(true);
JScrollPane scroller = new JScrollPane(textArea);//不需要自己去处理键盘事件,用下面的方法就可以了.
Document document = textArea.getDocument(); // 最主要的是这里
document.addDocumentListener(new DocumentListener(){
public void changedUpdate(DocumentEvent e) {
System.out.println("---change----");
}public void insertUpdate(DocumentEvent e) {
try {// 输入时,会输出当前textArea中的内容
Document document = e.getDocument();
System.out.println(document.getText(0, document.getLength()));
System.out.println("----Insert----");
} catch (BadLocationException blex) {}
}public void removeUpdate(DocumentEvent e) {
try {// 删除时,输出当前textArea中的内容
Document document = e.getDocument();
System.out.println(document.getText(0, document.getLength()));
System.out.println("----Remove----");
} catch (BadLocationException blex) {}
}
});frame.getContentPane().add(scroller);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}这个可以看一下,把JTextArea换成JTextField就行了.