• Java第三次作业第二题


    2. 【请复制本程序,作为java程序代码,进行编译,补充填写缺失代码部分,并实现题目要求功能,从而获得空白填写所需的内容。】

    定义3个线程,模拟红绿灯的效果

    一个线程控制画一个实心红圆

    一个线程控制画一个实心黄圆

    一个线程控制画一个实心绿圆

    红灯显示5秒,黄灯显示2秒,绿灯显示4秒

    按以上顺序交替进行。

    package naizi;
    import java.awt.*;
    import java.awt.event.*;
    @SuppressWarnings("serial")
    public class Tlight extends Frame implements WindowListener,ComponentListener{
    private int width = 200;
    private int height = 200;
    private Color color;
    class RedRunnable implements Runnable {
    public void run() {
    color = Color.RED;
    repaint();
    }
    }
    class GreeRunnable implements Runnable {
    public void run() {
    color = Color.GREEN;
    repaint();
    }
    }
    class YellowRunnable implements Runnable {
    public void run() {
    color = Color.YELLOW;
    repaint();
    }
    }
    Tlight(){
    super("traffic lights");
    this.setSize(width,height);
    this.setLocation(200, 200);
    this.setBackground(Color.white);
    this.setLayout(new FlowLayout());
    addWindowListener(this);
    addComponentListener(this);
    this.setVisible(true);
    }
    public void paint(Graphics g){ //绘图方法
    int x = width/6;
    int y  = height/3;
    g.setColor(color);;//设置颜色
    g.fillOval(x, y, 100, 100);//以x,y为圆心,100为半径画圆
    }
    public static void main(String[] args) throws InterruptedException{//抛出异常,请写具体类型
    Tlight t = new Tlight();
    RedRunnable red = t.new RedRunnable();
    GreeRunnable gree = t.new GreeRunnable();
    YellowRunnable yellow = t.new YellowRunnable();
    while(true){
    (new Thread(red)).run();//显示红色圆
    Thread.sleep(5000);//停5秒
    (new Thread(yellow)).run();//显示黄色圆
    Thread.sleep(2000);//停2秒
    (new Thread(gree)).run();//显示绿色圆
    Thread.sleep(4000);//停4秒
    }
    }
    public void componentResized(ComponentEvent e) {
    width = getWidth();
    height = getHeight();
    repaint();
    }
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    }
    public void windowOpened(WindowEvent e) {}
    public void windowClosed(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
    public void componentMoved(ComponentEvent e) {}
    public void componentShown(ComponentEvent e) {}
    public void componentHidden(ComponentEvent e) {}
    }
    

    测试截图如下:

  • 相关阅读:
    Redis
    多线程相关
    selenium操作浏览器的基本方法
    selenium之 webdriver与三大浏览器版本映射表(更新至v2.29)
    selenium安装及官方文档
    Python(3)_python对Json进行操作
    python类中的self参数和cls参数
    python3中shuffle函数
    Python3中assert断言
    python2和python3中range的区别
  • 原文地址:https://www.cnblogs.com/zqm-sau/p/10331735.html
Copyright © 2020-2023  润新知