问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
package com.edwin.lession03;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
public class light extends JFrame{
private static final long serialVersionUID = 1L;
private Thread t;
public light() {
setVisible(true);//设置窗体可见
setTitle("红绿灯模拟");//设置标题
setSize(600,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 x,int d) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
g2.fillRect(80, 120, 120, 40);
g2.fillRect(230, 120, 40, 40);
//绘制灯的外廓
g2.setColor(Color.GRAY);
g2.fillRect(55, 145, 10, 280);
g2.fillRect(55, 135, 30, 10);
g2.fillRect(200, 135, 30, 10);
//灯的杆子
g2.setColor(c);
g2.fillOval(x, 120 , 40, 40);
g2.setFont(new Font("楷体",Font.BOLD,40));
g2.drawString(d, 240, 155);
//绘制灯
}
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, 80,4);// 红灯
try {
Thread.sleep(2000); // 线程休眠2秒,红灯
} catch (InterruptedException e) {
e.printStackTrace();
}
this.paint(g, Color.green, 160,2);// 绿灯
try {
Thread.sleep(3000); // 线程休眠3秒,绿灯
} catch (InterruptedException e) {
e.printStackTrace();
}
this.paint(g, Color.yellow, 120,3);// 黄灯
}
}
}
public static void main(String[] args) { new light();
}
}
运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果
倒计时,在右面的方块里插入对应颜色的数字倒计时