编写选号程序,在窗体中安排6个标签,每个标签上显示0~9之间的以为数字,每位数字用一个线程控制其变化,点击“停止”按钮则所有标签停止变化
package test;
import
java.awt.Button;
import
java.awt.FlowLayout;
import
java.awt.Frame;
import
java.awt.Label;
import
java.awt.Panel;
import
java.awt.event.ActionEvent;
import
java.awt.event.ActionListener;
class MyLabel
extends Label implements Runnable{
int value;
boolean stop =false;
public MyLabel() {
super("number");
value =0;
}
public void run() {
for(;;) {
value=(int)(Math.random()*10);
setText(Integer.toString(value));
try {
Thread.sleep(500);
}catch(InterruptedException e) {}
if(stop)
break;
}
}
}
public class MyFrame extends Frame{
MyLabel x[]= new MyLabel[6];
Button control;
public MyFrame(String title) {
super(title);
Panel disp= new Panel();
disp.setLayout(new FlowLayout());
for(int i=0;i<6;i++) {
x[i]=new MyLabel();
disp.add(x[i]);
new Thread(x[i]).start();
}
add("Center",disp);
control = new Button("停止");
add("North",control);
pack();
setVisible(true);
control.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int i=0;i<6;i++)
x[i].stop = true;
}
}
);
}
public static void main(String args[]) {
new MyFrame("Test");
}
}