public class Test {
private Frame f;
private TextField t;
private TextArea ta;
private Button s;
Test() {
Frame f = new Frame("....");
f.setSize(300, 400);
f.setLocation(600, 300);
f.setLayout(new FlowLayout());
Button s = new Button("ok");
TextField t = new TextField(10);
TextArea ta = new TextArea(15, 20);
f.add(t);
f.add(s);
f.add(ta);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
s.addMouseListener(new MouseAdapter() {
// int count=1;
// int count1=1;
public void mouseClicked(MouseEvent e) {
// System.out.println("点击第"+(count++)+"下");
String a = t.getText();
// ta.append(a);
System.out.println(a);
}
});
t.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
但在其构造函数中又重复定义了一次
Frame f = new Frame("....");
Button s = new Button("ok");
TextField t = new TextField(10);
TextArea ta = new TextArea(15, 20);
结果就把原先的给覆盖了,从而这四个变量变成了局部变量,从而就导致了问题的出现,因为在添加监听器的时候用的是匿名内部类,试问一下能在一个类中访问到另外一个类的局部变量吗?显然是不可以的,所以其解决办法就是在构造函数中不再声明那四个变量的类型,
将其改为
f = new Frame("....");
s = new Button("ok");
t = new TextField(10);
ta = new TextArea(15, 20);