//楼主如果满意的话,设置我为满意答案,我就差你一个就10个了import java.awt.*;
import java.awt.event.*;class ThreadRect extends Frame implements Runnable ,ActionListener
{
Thread rect;
Rect redRect;
Button bt1,bt2;
//int x,y;
Boolean run=false;
public ThreadRect()
{
super("control the ball");
setLayout(null);
rect=new Thread(this);
redRect=new Rect(Color.red);
bt1=new Button("start");
bt2=new Button("quit");
bt1.setBounds(180,260,80,40);
bt2.setBounds(240,260,40,40);
bt1.addActionListener(this);
bt2.addActionListener(this);
add(redRect);
add(bt1);
add(bt2);
setSize(300,300);
}
public void run()
{
while(true)
{
int x=50,y=50;
for(int i=1;i<10;i++)
{
if(run){
x+=20;y+=20;
System.out.println (x+" "+y);
redRect.setLocation(x,y);
try {
Thread.sleep(1000);
}
catch (Exception ex) {
ex.printStackTrace();
}//如果不加此行将只看到最后一个结果
}
else{
stop();
}
}
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("start")){
//System.out.println ("start");
bt1.setLabel("pause");
bt2.setLabel("quit");
//bt1.setActionCommand("pause");
//bt2.setActionCommand("stop");
run=true;
rect.start();
}
if(e.getActionCommand().equals("quit")){
System.exit(0);
}
if(e.getActionCommand().equals("pause")){
bt1.setLabel("continue");
run=false;
}
if(e.getActionCommand().equals("continue")){
bt1.setLabel("pause");
run=true;
renew();
}
}
public synchronized void stop()
{
try {
wait();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public synchronized void renew()
{
notifyAll();
}
}class Rect extends Canvas
{
Color color;
public Rect(Color color)
{
setBounds(50,50,30,30);
this.color=color;
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillRect(0,0,20,20);
}
}class ThreadTest
{
public static void main(String[] args)
{
ThreadBall tb=new ThreadBall();
tb.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
tb.setVisible(true);
}
}
取消
评论