这个程序不能通过,找了一个小时错误,无奈中
这个程序不能通过,找了一个小时错误,无奈中:
import java.awt.*;
import java.awt.event.*;
public class TFMath {
public static void main(String args[]) {
new TFFrame().launchFrame();
}
}
class TFFrame extends Frame {
public void launchFrame() {
TextField num1 = new TextField(10),num2 = new TextField(10),num3 = new TextField(20);
Label lbPlus = new Label("+");
Button btEqual = new Button("=");
setVisible(true);
setLayout(new FlowLayout());
add(num1);
add(lbPlus);
add(num2);
add(btEqual);
add(num3);
pack();
btEqual.addActionListener(new Monitor(this));
}
}
class Monitor implements ActionListener {
TFFrame tf = null;
public Monitor(TFFrame tf) {
this.tf = tf;
}
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(tf.num1.getText());
int n2 = Integer.parseInt(tf.num2.getText());
tf.num3.setText(""+ (n1 + n2));
}
}
------解决方案--------------------把num1,num2, num3变成全局变量:
public TextField num1=null, num2=null, num3=null;
------解决方案--------------------import java.awt.*;
import java.awt.event.*;
public class TFMath {
public static void main(String args[]) {
new TFFrame().launchFrame();
}
}
class TFFrame extends Frame {
TextField num1 = new TextField(10), num2 = new TextField(10),
num3 = new TextField(20);
public void launchFrame() {
Label lbPlus = new Label("+");
Button btEqual = new Button("=");
setVisible(true);
setLayout(new FlowLayout());
add(num1);
add(lbPlus);
add(num2);
add(btEqual);
add(num3);
pack();
btEqual.addActionListener(new Monitor(this));
}
}
class Monitor implements ActionListener {
TFFrame tf = null;
public Monitor(TFFrame tf) {
this.tf = tf;
}
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(tf.num1.getText());
int n2 = Integer.parseInt(tf.num2.getText());
tf.num3.setText("" + (n1 + n2));
}
}