import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
class TestAwt extends Frame implements Runnable{
int num;
boolean temp = true;
Button bt = new Button("开始");
public TestAwt(){
this.setVisible(true);
this.setSize(400,300);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
bt.setSize(50,50);
this.add(bt,new BorderLayout().EAST);
bt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("开始")){
bt.setLabel("停止");
temp = false;
}
}
});
}
public void run(){
while(temp){
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
public void paint(Graphics g){
Dimension d =getSize();
int x =(int)(Math.random()*d.width);
int y =(int)(Math.random()*d.height);
Color c = g.getColor();
g.setColor(Color.red);
g.fillOval(x, y,10, 10);
g.setColor(c);
}
public static void main(String args[]){
TestAwt ta = new TestAwt();
Thread thread = new Thread(ta);
thread.run();
}
}
|