Kadir Akpolat
Kadir Akpolat

Reputation: 31

Java Multithreading with GUI (Kind of Traffic Simulator)

I need to implement a solution for a narrow bridge and i am new to java threads and gui. I have three roads and 1 bridge(has two lane).20 Vehicles for each road should be created randomly and should get passed to bridge depending of the light on its road.

But first I just wanna solve an easy issue which is how can i move a car on this road with thread?(Sleep 1 second and move little bit.)

I thought like that: I have created the roads with simple PaintComponent function override(I am not sure if its gonna be implemented like that too). Created a road class and a vehicle class which implements runnable. I created an array of 20 vehicles in Road class and stuck here.

How should I add this to a JPanel and move it right every 1 seconds? Am I totally wrong about how to implement that problem because i have background on C family ?

My Code:

public class NarrowBridge {

public static void main(String[] args) {



    JFrame myFrame = new JFrame();
    PanelSetter newPanel = new PanelSetter();
    myFrame.add(newPanel);
    myFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    myFrame.setSize(600, 600);
    myFrame.setTitle("Narrow Bridge Problem ");

    myFrame.setLocationRelativeTo(null);//To centralize the jframe.
    myFrame.setVisible(true);

}

}

class PanelSetter extends JPanel {

public Road Road1 = new Road(true);
public Road Road2 = new Road(false);
public Road Road3 = new Road(false);

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);


    //Fixed Roads Drawing.
    g.setColor(Color.BLACK);
    g.drawLine(50, 100, 200, 100);
    g.drawLine(50, 130, 200, 130);

    g.setColor(Color.BLACK);
    g.drawLine(50, 210, 200, 210);
    g.drawLine(50, 240, 200, 240);

    g.setColor(Color.BLACK);
    g.drawLine(50, 320, 200, 320);
    g.drawLine(50, 350, 200, 350);


    //Road 1 Light.
    if (Road1.getLight()) {

        g.setColor(Color.GREEN);
        g.fillOval(180, 70, 20, 20);

    } else {
        g.setColor(Color.RED);
        g.fillOval(180, 70, 20, 20);

    }
    //Road 2 Light.
    if (Road2.getLight()) {
        g.setColor(Color.GREEN);
        g.fillOval(180, 180, 20, 20);

    } else {
        g.setColor(Color.RED);
        g.fillOval(180, 180, 20, 20);

    }
    //Road 3 Light. 
    if (Road3.getLight()) {
        g.setColor(Color.GREEN);
        g.fillOval(180, 290, 20, 20);

    } else {
        g.setColor(Color.RED);
        g.fillOval(180, 290, 20, 20);

    }

}

}

Road is just a simple class which only has boolean light and the thing i tried which is vehicle[] vehicles=new vehicle[20].

Upvotes: 1

Views: 661

Answers (1)

Kadir Akpolat
Kadir Akpolat

Reputation: 31

Finally i solved my problem with the help of Java Applets. I am able to pass the applet as a parameter and I am calling it's paint() function and updating screen.

Upvotes: 2

Related Questions