日期:2014-05-20  浏览次数:20740 次

《菜鸟求助》一个持有对方引用的问题
import java.awt.*;
import java.awt.event.*;


public class Test45 {
  public static void main(String args[]){
new MyFrame().launch();
  }
}

class MyFrame extends Frame{
public void launch(){
FlowLayout f = new FlowLayout();
TextField tf1 = new TextField(10);
TextField tf2 = new TextField(10);
TextField tf3 = new TextField(15);
Label l1 = new Label("+");
Button b = new Button("=");
setLayout(f);
add(tf1);
add(l1);
add(tf2);
add(b);
add(tf3);
b.addActionListener(new Listener(this));
pack();
setVisible(true);
}



}

class Listener implements ActionListener {
  MyFrame mf = null;
Listener(MyFrame mf){
this.mf= mf;
}

public void actionPerformed(ActionEvent w){
int num1 = Integer.parseInt(mf.tf1.getText());
int num2 = Integer.parseInt(mf.tf2.getText());
mf.tf3.setText(" "+ (num1+num2));
}
}

为什么mf.tf1.getText()
mf.tf2.getText()
mf.tf3.getText()

会报错 我哪里写错了 谢谢啊

------解决方案--------------------
tf1 和 tf2是void launch()方法的局部变量 就算是全局变量 那也要设为公有的 或者 写set get 方法
------解决方案--------------------
MyFrame在main函数里new,就调用那个
------解决方案--------------------
Java code



package com.yxk.test;

/**
 * ClassName:MyFrame
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author   yxk
 * @version 1.0 2011-9-13
 * @since 1.0
 * @see
 */
import java.awt.*;
import java.awt.event.*;

public class MyFrame extends Frame implements ActionListener{
    /**
     * @Description: TODO(添加属性注释)
     */
    private static final long serialVersionUID = 1L;
    public FlowLayout f = new FlowLayout();
    public TextField tf1 = new TextField(10);
    public TextField tf2 = new TextField(10);
    public TextField tf3 = new TextField(15);
    public Label l1 = new Label("+");
    public Button b = new Button("=");

    public MyFrame() {
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    }

    public void launch() {

        setLayout(f);
        add(tf1);
        add(l1);
        add(tf2);
        add(b);
        add(tf3);
        b.addActionListener(this);
        pack();
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        
        int num1 = Integer.parseInt(tf1.getText());
        int num2 = Integer.parseInt(tf2.getText());
        tf3.setText(" " + (num1 + num2));
        
    }

    public static void main(String[] args) {
        new MyFrame().launch();
    }

}

------解决方案--------------------
错误是不是找不到变量,你那几个tf1,tf2,tf3,在方法里面声明的!对像是找不到的!
你把他改成成员变量,然后在方法里面实例化;但注意的是,这些成员变量一定要在点用前实例化,否着会报nullclassexception