import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class ShiYan04 {
public static void main(String args[])
{
Ckou ck=new Ckou();
}
}
class Ckou extends JFrame
{
public Ckou()
{
JFrame jframe=new JFrame("变色圆");
Container container=jframe.getContentPane();
jframe.setBackground(Color.BLUE);
jframe.setSize(600,400);
jframe.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jframe.setVisible(true);
Drawt dt=new Drawt();
container.add(dt);
JButton button=new JButton("开始");
button.setSize(30, 30);
container.add(button);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
T2 t2=new T2(dt);
Thread tt2=new Thread(t2);
T1 t1=new T1(dt,t2);
Thread tt1=new Thread(t1);
tt1.start();
tt2.start();
try
{
Thread.sleep(100000);
}
catch(Exception e3)
{}
}
}
);
}
class T1 implements Runnable
{
Drawt t;
T2 a;
public T1(Drawt t,T2 a)
{
this.t=t;
this.a=a;
}
public void run()
{
while(true)
{
System.out.println("现在显示绿色");
a.stop=true;
t.i=1;
t.repaint();
try
{
Thread.sleep(3000);
}
catch(Exception e1)
{}
a.stop=false;
try
{
Thread.sleep(3000);
}
catch(Exception e1)
{}
}
}
}
class T2 implements Runnable
{
volatile boolean stop = true;
Drawt t;
public T2(Drawt t)
{
this.t=t;
}
public void run()
{
while(!stop)
{
System.out.println("现在显示红色");
t.i=2;
try
{
Thread.sleep(3000);
}
catch(Exception e2)
{}
}
}
}
class Drawt extends JPanel
{
int i=0;
public Drawt()
{}
public void paint(Graphics g)
{
if(i==1)
{
g.setColor(Color.green);
g.drawOval(100,100,70, 70);
}
else if(i==2)
{
g.setColor(Color.red);
g.drawOval(150,150,70, 70);
}
}
}
}
首先他一直输出的是绿色的圆,
然后就是由于加上主线程main的睡眠,我的圆显示不出来