- Java code
import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Test { public static void main(String[] args) { EventQueue.invokeLater(new Runnable(){ public void run(){ MyFrame frame=new MyFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }); }}class MyFrame extends JFrame{ public MyFrame(){ Toolkit kit=Toolkit.getDefaultToolkit(); Dimension screenSize=kit.getScreenSize(); setSize(screenSize.width/2,screenSize.height/2); setLocation(100,100); setVisible(true); TextField tf1=new TextField(10); TextField tf2=new TextField(10); TextField tf3=new TextField(20); Label equal=new Label("+"); Panel p=new Panel(); Button b=new Button("="); p.add(tf1); p.add(equal); p.add(tf2); p.add(b); p.add(tf3); add(p); Monitor m=new Monitor(this); b.addActionListener(m); pack(); }}class Monitor implements ActionListener{ MyFrame mf=null; public Monitor(MyFrame mf){ this.mf=mf; } public void actionPerformed(ActionEvent e) {* double a=Double.parseDouble(mf.tf1.getText());* double bb=Double.parseDouble(mf.tf2.getText());* mf.tf3.setText(""+(a+bb)); } }
*行报错,好像是和tf1,tf2,tf3有关,可是 不是在MyFrame 中定义了吗 为什么还是不对呢?
先谢谢各位了
------解决方案--------------------
- Java code
class MyFrame extends JFrame{ public MyFrame(){ Toolkit kit=Toolkit.getDefaultToolkit(); Dimension screenSize=kit.getScreenSize(); setSize(screenSize.width/2,screenSize.height/2); setLocation(100,100); setVisible(true); //TextField tf1=new TextField(10); //这样定义的是局部变量,方法内有效,方法外无法访问 //TextField tf2=new TextField(10); //TextField tf3=new TextField(20); Label equal=new Label("+"); Panel p=new Panel(); Button b=new Button("="); p.add(tf1); p.add(equal); p.add(tf2); p.add(b); p.add(tf3); add(p); Monitor m=new Monitor(this); b.addActionListener(m); pack(); } TextField tf1=new TextField(10); //这样定义的是成员变量,这里没有public修饰 TextField tf2=new TextField(10); //同一个包的外部类可以访问 TextField tf3=new TextField(20);}