import java.awt.*;
import java.awt.event.*;
public class moveButton extends Frame implements Runnable,ActionListener
{
Thread first,second,third;
Button redbutton,greenbutton,yellowbutton,startbutton;
int distance=10;
moveButton()
{
first=new Thread(this);
second=new Thread(this);
third=new Thread(this);
redbutton=new Button();
greenbutton=new Button();
yellowbutton=new Button();
redbutton.setBackground(Color.red);
greenbutton.setBackground(Color.green);
yellowbutton.setBackground(Color.yellow);
startbutton=new Button("star");
startbutton.addActionListener(this);
setLayout(null);
add(redbutton);
redbutton.setBounds(10,60,15,15);
add(greenbutton);
greenbutton.setBounds(100,60,15,15);
add(yellowbutton);
yellowbutton.setBounds(200,60,15,15);
add(startbutton);
startbutton.setBounds(10,100,30,30);
setBounds(0,0,300,200);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{
try
{
first.start();
second.start();
third.start();
}
catch(Exception exp){}
}
public void run()
{
while(true)
{
if(Thread.currentThread()==first)
{
moveComponent(redbutton);
try
{
Thread.sleep(20);
}
catch(Exception exp){}
}
if(Thread.currentThread()==second)
{
moveComponent(greenbutton);
try
{
Thread.sleep(10);
}
catch(Exception exp){}
}
if(Thread.currentThread()==third)
{
moveComponent(yellowbutton);
try
{
Thread.sleep(5);
}
catch(Exception exp){}
}
}
}
public synchronized void moveComponent(Component b)
{
if(Thread.currentThread()==first)
{
while(distance>100&&distance<=300)
try{
wait();
}catch(Exception exp){}
distance=distance+1;
b.setLocation(distance,60);
if(distance>=100)
{
b.setLocation(10,60);
notifyAll();
}
}
if(Thread.currentThread()==second)
{
while(distance>=10&&distance<100||distance>=200&&distance<300)
try{
wait();
}catch(Exception exp){}
distance=distance+1;
b.setLocation(distance,60);
if(distance>200)
{
//distance=200;
b.setLocation(100,60);
notifyAll();
}
}
if(Thread.currentThread()==third)
{
while(distance>=10&&distance<200)
try{
wait();
}catch(Exception exp){}
distance=distance+1;
b.setLocation(distance,60);
if(distance>300)
{
distance=10;
b.setLocation(200,60);
notifyAll();
}
}
}
}public class Move
{
public static void main(String args[])
{
new moveButton();
}
}
老师布置的作业,三个按钮,第一个红的先运动10-100,碰到第二个绿色的按钮,红色的回到10,绿色的运动100-200,碰到第三个黄色的,绿色的回到200,黄色的运动200-300,然后回到200.然后这样循环。start按钮开始。我做的只有前两个按钮,四三个怎么不显示呢
{
while(distance>=10&&distance<100||distance>=200&&distance<300)
try{
wait();
}catch(Exception exp){}
distance=distance+1;
b.setLocation(distance,60);
if(distance>=200)
{
//distance=200;
b.setLocation(100,60);
notifyAll();
}
}
//distance=200
注释去掉
注释去掉