日期:2014-05-20 浏览次数:20732 次
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)); } }
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); }