今天看了书本线程和绘图的一部分,翻了翻书本,发现一道课后习题是要模拟红绿灯变化,好像有点意思,嘿嘿嘿,我就来写了写,不喜勿喷,大家可以多多指正~
运行起来是这样的
(第一次上传代码有点紧张 [擦擦手手的汗] )
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
public class light extends JFrame{
/**
* 模拟红绿灯,红灯2秒,绿灯3秒,黄灯4秒
*/
private static final long serialVersionUID = 1L;
private Thread t;
public light() {
setVisible(true);//设置窗体可见
setTitle("红绿灯模拟");//设置标题
setSize(100,600);//窗体大小
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//窗体关闭模式
Canv c = new Canv();
add(c);//窗体作为画布
t = new Thread(c);//创建匿名线程对象
t.start();//启动线程
}
class Canv extends Canvas implements Runnable{//创建画布(内部类)
/**
*
*/
private static final long serialVersionUID = 1L;
public void paint(Graphics g,Color c,int y) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
g2.fillRect(40, 40, 40, 120);//绘制灯的外廓
g2.setColor(Color.black);
g2.fillRect(55, 160, 10, 270);//灯的杆子
g2.setColor(c);
g2.fillOval(40, y, 40, 40);//绘制灯
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {//无限循环
try {
Thread.sleep(4000); // 线程休眠4秒,黄灯
} catch (InterruptedException e) {
e.printStackTrace();
}
Graphics g = getGraphics();
this.paint(g, Color.red, 40);// 红灯
try {
Thread.sleep(2000); // 线程休眠2秒,红灯
} catch (InterruptedException e) {
e.printStackTrace();
}
this.paint(g, Color.green, 80);// 绿灯
try {
Thread.sleep(3000); // 线程休眠3秒,绿灯
} catch (InterruptedException e) {
e.printStackTrace();
}
this.paint(g, Color.yellow, 120);// 黄灯
}
}
}
public static void main(String[] args) {
new light();
}
}