请问下面代码中tf.addTextListener(this);出错,请问如何改  SWING中的文本框如何添加文本事件的监听器,import java.awt.*;
import java.awt.event.*;
import javax.swing.*;public class JTx  extends  JFrame  implements  TextListener, ActionListener 
   {  JTextField    tf;
      JTextArea    ta; 
  public JTx()
  { tf=new JTextField(45);
     ta=new JTextArea(10,45);
    setLayout(new FlowLayout());
    
    this.getContentPane().add(tf);
    this.getContentPane().add(ta);
    
        tf.addActionListener(this);
       
    tf.addTextListener(this);
      setSize(300,500);
       setVisible(true);
  }
  public  void  textValueChanged(TextEvent e)
{   if(e.getSource()==tf)
   ta.setText(((TextField)e.getSource()).getText());
   
}
public  void actionPerformed(ActionEvent  e)
{if(e.getSource( )==tf)
   ta.setText("");
}
    public static void main(String args[]) {
        
  new  Tx();
    }
}

解决方案 »

  1.   

    TextField有  ,JTextField沒有
      

  2.   

    DocumentListener接口里有public void insertUpdate(DocumentEvent e) {}public void removeUpdate(DocumentEvent e) {}public void changedUpdate(DocumentEvent e) {}
      

  3.   

    public class JTx  extends  JFrame  implements  TextListener, ActionListener {
    ...
    ...
    DocumentListener textListener =
        new DocumentListener(){
            public void changedUpdate(DocumentEvent e){
             System.out.println(e.getDocument().getProperty("SERV_FOR") + ": changed");
            }
            public void insertUpdate(DocumentEvent e){
             System.out.println(e.getDocument().getProperty("SERV_FOR") + ": insert");
            }
            public void removeUpdate(DocumentEvent e){
             System.out.println(e.getDocument().getProperty("SERV_FOR") + ": update");         
            }
        };
    public JTx() {
    tf = new JTextField(45);
    ta = new JTextArea(10, 45);
    setLayout(new FlowLayout()); this.getContentPane().add(tf);
    this.getContentPane().add(ta); tf.addActionListener(this);

    Document doc;
    doc = tf.getDocument();
    doc.putProperty("SERV_FOR", tf);
    doc.addDocumentListener(textListener);

    doc = ta.getDocument();
    doc.putProperty("SERV_FOR", ta);
    doc.addDocumentListener(textListener);
    ...
    ...
    }
    }
      

  4.   

    你注册的时候是用this做为监听器的,可是你实现的时候,却是另外写了 一个类,而并没有在本类中实现事件接口中的方法,这样当然是通过不了编译的了