当前位置:主页 >> Java基础 >> 正文
java实现监听JTextfield内容的改变
阅读:151 输入:2014-05-22 07:01:39
package pretoct;
 
import javax.swing.JFrame;  
import javax.swing.JPanel;  
import javax.swing.JTextField;  
import javax.swing.event.DocumentEvent;  
import javax.swing.event.DocumentListener;  
import javax.swing.text.Document;  
  
public class test extends JFrame implements DocumentListener{  
    public static void main(String[] args){  
        new test().init();  
    }  
      
    JPanel contentPanel;  
    JTextField textField;  
    public void init(){  
        contentPanel = new JPanel();  
        setContentPane(contentPanel);  
        contentPanel.setBounds(400,200,400,400);  
          
        textField = new JTextField();  
        textField.setBounds(0, 0, 100, 30);  
        textField.setColumns(10);  
          
        //关键是下面这两行代码  
        Document document = textField.getDocument();  
        document.addDocumentListener(this);  
          
        contentPanel.add(textField);  
          
        this.setVisible(true);  
        this.setSize(500, 400);  
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
    }  
  
    @Override  
    public void insertUpdate(DocumentEvent e) {  
        System.out.println("insert text");  
    }  
  
    @Override  
    public void removeUpdate(DocumentEvent e) {  
        System.out.println("remove text");  
    }  
  
    @Override  
    public void changedUpdate(DocumentEvent e) {  
        System.out.println("change text");  
    }  
}