请问下面代码中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();
}
}
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();
}
}
...
...
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);
...
...
}
}