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

这个程序为什么不能运行,是我设的引用错误么?
Java code

import java.awt.*;
import java.awt.event.*;

public class TFmath{
    public static void main(String[] args){
        new MyFrame();
        }
    }
    
class MyFrame extends Frame{
    public MyFrame(){
        setLayout(new FlowLayout());
        TextField num1 = new TextField(10);
        TextField num2 = new TextField(10);
        TextField num3 = new TextField(15);        
        Label lab = new Label("+");        
        Button bun = new Button("=");
        bun.addActionListener(new minitor(this));
        add(num1);
        add(lab);        
        add(num2);        
        add(bun);
        add(num3);        
        pack();
        setVisible(true);        
        }
    }    
    
class Minitor implements ActionListener{

    MyFrame mf = null;
    Minitor(MyFrame mf){
        this.mf = mf;
        }
        
    public void actionPerformed(ActionEvent e){
        int n1 = Integer.parseInt(mf.num1.getText());
        int n2 = Integer.parseInt(mf.num2.getText());
        int n3 = (n1 + n2);
        mf.num3.setText(String.valueOf(n3));        
        }
    }



------解决方案--------------------
2大问题:

1、不能去引用局部变量
int n1 = Integer.parseInt(mf.num1.getText());
int n2 = Integer.parseInt(mf.num2.getText());
要改正的话,应该是把这三句话中定义的变量,变成成员变量:
TextField num1 = new TextField(10);
TextField num2 = new TextField(10);
TextField num3 = new TextField(15);
也就是放到 public MyFrame(){ 前面去。

2、大小写错误
bun.addActionListener(new minitor(this));
应该是 new Minitor