public class ZH extends JFrame implements TextListener //有错
{
public ZH()
{
setTitle("转换");
Container con=getContentPane();
con.setLayout(new GridLayout(4,2));
JLabel l1=new JLabel("原身份证号");
JLabel l2=new JLabel("转换后的身份证号");
JTextField t1=new JTextField(20);
JTextField t2=new JTextField(20);
con.add(l1);con.add(t1);con.add(l2);con.add(t2);
t1.addTextListener(this); //有错
setSize(300,150);
setVisible(true);
}
public static void main(String args[])
{
new ZH();
} public void textValueChanged(TextEvent e)
{
//事件处理代码
}}
{
public ZH()
{
setTitle("转换");
Container con=getContentPane();
con.setLayout(new GridLayout(4,2));
JLabel l1=new JLabel("原身份证号");
JLabel l2=new JLabel("转换后的身份证号");
JTextField t1=new JTextField(20);
JTextField t2=new JTextField(20);
con.add(l1);con.add(t1);con.add(l2);con.add(t2);
t1.addTextListener(this); //有错
setSize(300,150);
setVisible(true);
}
public static void main(String args[])
{
new ZH();
} public void textValueChanged(TextEvent e)
{
//事件处理代码
}}
t1.addTextListener(this); 这句还是报错textValueChanged这个方法和textChanged方法有什么不同?
不过就我去过的CSDN版块中 JAVA是最差的
1、如果你要实现一个事件接口,就必须重写这个接口的所有事件
这里你实现了TextListener接口,就需要实现
public void textValueChanged(TextEvent e)
{
//事件处理代码
}
当然代码可以为空,那就是什么都不处理2、由于TextField不止一个,并不是所有的TextField需要响应事件,所以要为那些需要响应的组件加上事件监听:
t1.addTextListener(this);
这里参数代表实现事件的类,这里由于是ZH这个类实现的,所以用this这时,当t1的内容发生变化时,就会调用textValueChanged方法了。而t2不会有反应。3、JTextField属于swing,TextField属于awt,两者的事件处理方法不尽相同
所以在awt,TextField可以响应textValueChanged事件,而JTextField不是这样处理的,没有用过,查资料看好像是用DocumentListener4、下面是使用TextField的示例,当t1内容改变时,t2复制其内容。从你程序功能看应该是当t1输入结束后再改变t2的值,这时可以考虑使用ActionListenerimport java.awt.*;
import java.awt.event.*;
import javax.swing.*;public class ZH extends JFrame implements TextListener
{
JLabel l1;
JLabel l2;
TextField t1;
TextField t2;
public ZH()
{
setTitle("转换");
Container con=getContentPane();
con.setLayout(new GridLayout(4,2));
l1=new JLabel("原身份证号");
l2=new JLabel("转换后的身份证号");
t1=new TextField(20);
t2=new TextField(20);
con.add(l1);con.add(t1);con.add(l2);con.add(t2);
t1.addTextListener(this);
setSize(300,150);
setVisible(true);
}
public void textValueChanged(TextEvent e)
{ t2.setText(t1.getText());
}
public static void main(String args[])
{
new ZH();
}
}