站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题程序哪里有错啊

程序哪里有错啊

摘要: 程序哪里有错啊


import java.awt.*;
import java.awt.event.*;
class Myframe extends Frame implements ActionListener
{TextField text1,text2;
Myframe(String s)
{super(s);
setLayout(new FlowLayout());
TextField text1=new TextField(10);
TextField text2=new TextField(10);
add(text1);
text1.addActionListener(this);
add(text2);
setBounds(20,30,300,200);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{System.exit(0);}
});
}
public void actionPerformed(ActionEvent e)
{if(e.getSource()==text1)
text2.setText(text1.getText());}

}
class Test
{public static void main(String args[])

{new Myframe("窗口");}
}

怎么改text2这个文本框总是什么反应都没有,各位试试,哪里有错啊?


text1和text2的声明位置不对,因为你在actionPerformed方法中要用。
class Myframe extends Frame implements ActionListener
{TextField text1=new TextField(10);
TextField text2=new TextField(10);
Myframe(String s)
.......
.......


原来如此,唉,我太大意了!谢谢了,结贴!


初始化的位置也是很重要的。像你这样的情况,最好在你声明变量的时候就初始化。


结贴太早了,还请各位补充一下:
为什么我在书上看到的例子这样是可以的:
class Myframe extends Frame implements ActionListener
{TextField text1=new TextField(10);
TextField text2=new TextField(10);
Myframe(String s)
{super(s);
text1=new TextField(10);
text2=new TextField(10);}}
却是可以的????


↑返回目录
前一篇: 请推荐几个有名的java网站或者论坛
后一篇: 参数前面为什么要加"-"号?