简体   繁体   中英

Traffic simulation in Java- Traffic Light s not showing up

I'm trying to create a traffic simulation with a few cars, and an ambulance and traffic lights at an intersection. I trying to measure the time it takes for the ambulance to move through traffic. I However I'm seeing the cars (about 3) but I'm not sure how to get the traffic lights to show up.

I used a canvas to draw on and to specify parameters for each object such as cars, ambulance, stop line, etc. When I tried to do the same for a traffic light object it doesn't show up- then i tried specifying the parameters (color, x & y coordinates, and diameter) from my drawlight method but still nothing shows up.

Can anyone help me at least get the traffics lights showing up? Thanks

Here's the code:

/**
     * Author:  Jean-Paul Fernandes
     * ******TRAFFIC SIMULATION******
     * 
 *  *****************TrafficCanvas Class******************
 *
 */
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;

public class TrafficCanvas extends Canvas {
/**
 * 
 */
public static final long serialVersionUID = 1L;
VehicleObject car, car_b, ambulance, ambulance_b;
String message, mode = "hi";
String str_seconds = "";
Boolean end;
StopLine stopline1, stopline2, stopline3, stopline4;
//  TrafficLight2 wrson_dock_rd_tl_east_facing;
TrafficLight t1;
int count, seconds;
//  TrafficFixtureForward westBound, eastBound, northBound;
//  TrafficFixtureTurn turn;

//  drawLine(20, 100, 120, 100);

public TrafficCanvas() {
    super();
    // TODO Auto-generated constructor stub

    car = new Car(195,240,20,15,Color.BLUE,Color.GREEN);
    //  creates a blue car with specified dimension & location
    car_b = new Car(215,280,20,15,Color.ORANGE,Color.GREEN);

    ambulance = new Ambulance(300,240,30,17,Color.RED,Color.BLACK,false);
    //  creates a red ambulance in emergency mode
//  if (count == 10)
    {
    ambulance_b = new Ambulance(350,280,30,17,Color.BLUE,Color.BLACK,true);
    //  creates another ambulance
    }


    stopline1 = new StopLine (250,240,5,25,Color.GRAY,Color.BLACK);
    stopline2 = new StopLine (320,280,5,25,Color.GRAY,Color.BLACK);
    stopline3 = new StopLine (260,300,25,5,Color.GRAY,Color.BLACK);
    stopline4 = new StopLine (290,235,25,5,Color.GRAY,Color.BLACK);

//  t1 = new TrafficLight (Color.RED, Color.YELLOW, Color.GREEN,
//          200,100,100,200,100,100,200,100,100);

//  wrson_dock_rd_tl_east_facing = new TrafficLight2 ();


    Thread movetraffic = new Traffic();
    movetraffic.start();//  moves traffic along

    Thread starttimer = new Timer();
    starttimer.start();

    Thread operatetraf_lights = new TrafficController();
    operatetraf_lights.start();

    /*Thread operatetraf_lights1 = new TrafficFixtureForward(message, count);
    operatetraf_lights1.start();*/

} //    end TrafficCanvas



public void paint(Graphics g){

    Graphics2D g2=(Graphics2D)g;

    car.draw(g2);
    car_b.draw(g2);
    ambulance.draw(g2);

    if (count>=10) 
    ambulance_b.draw(g2);

    stopline1.draw(g2);
    stopline2.draw(g2);
    stopline3.draw(g2);
    stopline4.draw(g2);

This next line is where I'm trying to create the red light of the traffic light:

    t1.drawLight(g2, Color.RED, 500,500,75,75); // draw red light


    {
        g2.drawString(mode,600,300);
    }
        g2.drawString (str_seconds, 200, 200);
    try {
//      if (end)
        {
        g2.drawString("End!",400,300);
        }
    } catch (NullPointerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}// end paint

public class TrafficController extends Thread {
    public void run() {
        t1 = new TrafficLight ();

    }
}

public class Timer extends Thread {
    public void run() {

        for (seconds = 0; seconds < 101; seconds++) {

            str_seconds = Integer.toString(seconds)+ " seconds";
            repaint();
            try{
                sleep(1000);
            }
            catch(InterruptedException e){}//end of try catch block
        }   // end for

        repaint();
    }   //  end run()
}   // end class Timer

public class Traffic extends Thread {

    public void run(){
        Car c1 =(Car) car; //   creates a car object c1
        Car d1 =(Car) car_b; 
        Ambulance a1 =(Ambulance) ambulance; 
//  creates an ambulance  object a1
        Ambulance b1 =(Ambulance) ambulance_b;

        if (count >=10) {
            if (ambulance_b.EmergencyMode()) {
                mode = "Emergency!";
            } else {
                mode = "Normal";
            }
        }
        for (int count = 0; count < 50; count++) {

            if (!(c1.shape().intersects(stopline1.shape()
.getBounds2D()))){
                c1.moveEast();
            }
            a1.moveEast();

            if (count>=10) {

                if (!(b1.shape().intersects(stopline2.shape()
.getBounds2D()))) {
                    b1.moveWest();
                }
            }
            d1.moveWest();

            repaint();
            try{
                sleep(500);
            }
            catch(InterruptedException e){}//end of try catch block

            if(c1.shape().intersects(stopline1.shape().getBounds2D())){

            }

            c1.setXcord(c1.getXcord());
            c1.setYcord(c1.getYcord());
            a1.setXcord(a1.getXcord()+ 1);
            a1.setYcord(a1.getYcord());
            if (count>10) {
                b1.setXcord(b1.getXcord()+ 1);
            b1.setYcord(b1.getYcord());
            }

        }
        end = true;
        message = "End!";
        repaint();

    }// end run
}// end class Traffic



}// end class TrafficCanvas

TrafficLight.java

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import java.awt.*;

import javax.swing.JPanel;


public class TrafficLight 

     /**
     * 
     */
    private static final long serialVersionUID = 1L;
    Color RedColor, YellowColor, GreenColor;
      int RedxLCord, RedyLCord, RedLDiam, YellowxLCord, YellowyLCord, YellowLDiam, GreenxLCord, GreenyLCord, GreenLDiam;

    public Shape shape(){
        return new Rectangle2D.Double(500,500,200,600);
    }   

    /*public TrafficLight(Color RedColor, Color YellowColor, Color GreenColor, 
            int RedxLCord, int RedyLCord, int RedLDiam, 
            int YellowxLCord, int YellowyLCord, int YellowLDiam, 
            int GreenxLCord, int GreenyLCord, int GreenLDiam)
    {

    }*/
    public TrafficLight() {
    }

    /*public void paintComponent (Graphics g) {
        super.paintComponent(g);
        g.drawRect(10,20,10,10);
        g.fillRect(10,20,10,10);
    }*/


      public void drawLight(Graphics2D g2, Color Colour, int RedxLCord, int RedyLCord, int RedLDiam, int RedLDiam1 ) {


    g2.setColor( Colour );
    g2.fillOval(RedxLCord,RedyLCord,RedLDiam1,RedLDiam1);



    }
}

SimulationFrame.java

import java.awt.*;
import java.awt.Canvas;
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class SimulationFrame extends JFrame{

    /**
     * @param args
     */
    Canvas c;

    public SimulationFrame() {
         c = new TrafficCanvas();
        add(c,BorderLayout.CENTER);
        setSize(1000,800);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    //  This is the Main class which runs the program & creates a window on screen

    public static void main(String[] args) {
        SimulationFrame frame = new SimulationFrame();

    }// end main method

} //    end class SimulationFrame

EDIT:

The lights are showing but I can't get them to change- I have a TrafficController thread here:

public void run(Graphics2D g) {
//      Graphics2D g = null;
        //  g3.drawString("TrafficController",400,300);
    //  Graphics2D g3=(Graphics2D)g;

        TrafficLight tr1 = (TrafficLight)t1;
        t1.drawLight(g,3);// show green
        try {
            sleep(500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        t1.drawLight(g,2);//    show yellow
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
        t1.drawLight(g,1);//    show red
        try {
            Thread.sleep(150);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        repaint();

    }

Without trying to understand the huge amount of code posted, there is one thing you should certainly change. AWT/Swing requires all GUI operations to happen on the AWT Event Queue thread. As long as you have your own threads directly calling AWT/Swing methods you are bound to see all sorts of random update/paint issues, if not worse.

For a very simple throwaway piece of code, you might get away with running everything on the Event Queue thread entirely (at the cost of having an unresponsive GUI while it's simulating something). Otherwise you'll probably want to have two threads, one (in practice, your application's main thread) performing simulations, and the other being the Event Queue where you do all your GUI updates.

Useful reading to get you started with design: http://en.wikipedia.org/wiki/Event_dispatching_thread

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM