//我们用一个合成的applet/application来简单显示出一个计数器的结果
/**
* Created by qichunlin on 2017/10/12.
*/
/*简单的计数器*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Counter extends Applet {
private int count =0;
private Button onOff=new Button("Toggle");//初始化两个按钮
private Button start=new Button("Start");
private TextField t=new TextField(10);//初始化文本字段对象
private boolean runFlag=true;
private long i=0; //循环变量
public void init(){
add(t);
start.addActionListener(new StartL()); //注册按钮
add(start); //放置按钮
}
public void go(){
while(true){
i=0;
while (i<=10000000){
i++;
} //花费近千万毫秒的时间,密集计算
if(runFlag) //一旦开始,CPU没机会执行其他代码,耗费时间
t.setText(Integer.toString(count++));
}
}
class StartL implements ActionListener
{
public void actionPerformed(ActionEvent e) //内部类,实现接口,响应按钮单击事件,其实没执行的机会
{
go(); //注1
}
}
class OnOffL implements ActionListener{
public void actionPerformed(ActionEvent e) //内部类,实现接口,响应按钮单击事件,其实没执行的机会
{
runFlag=!runFlag;
}
}
public static void main(String[] args)
{
Counter1 applet= new Counter1();
Frame aFrame=new Frame("Counter1");
aFrame.addWindowListener(new WindowAdapter() { //关闭框架按钮事件,没机会执行
public void windowCloseing(WindowEvent e){
System.exit(0);
}
});
aFrame.add(applet,BorderLayout.CENTER);
aFrame.setSize(300,200);
applet.init();
applet.start();
aFrame.setVisible(true);
}
}