Package trafficlight

Source Code of trafficlight.Light

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package trafficlight;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JPanel;

/**
*
* @author ADIKSONLINE
*/
public class Light extends JPanel {

    private int current = 0;
    private Timer timer = new Timer();

    public Light() {
        doNext();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setColor(Color.GRAY);
        g2d.drawRect(20, 20, 140, 380);

        if (current == 0 || current == 1) {
            g.setColor(Color.RED);
        } else {
            g.setColor(Color.GRAY);
        }
        g2d.fillOval(40, 40, 100, 100);
        switch (current) {
            case 1:
            case 3:
                g.setColor(Color.YELLOW);
                break;
            default:
                g.setColor(Color.GRAY);
        }
        g2d.fillOval(40, 160, 100, 100);
        if (current == 2) {
            g.setColor(Color.GREEN);
        } else {
            g.setColor(Color.GRAY);
        }
        g2d.fillOval(40, 280, 100, 100);
    }

    public void doNext() {
        int delay;
        switch (current) {
            case 0:
            case 2:
                delay = 6000;
                break;
            case 1:
            case 3:
            default:
                delay = 1000;
                break;
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                current = ++current % 4;
                repaint();
                doNext();
            }
        }, delay);

    }
}
TOP

Related Classes of trafficlight.Light

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.