import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; public class Road extends JPanel { private Car car1;//only one car on system private Timer t;//motion private Graphics myBuffer;//graphics public Road() { car1= new Car(0,440);//create car in second lane t = new Timer(10000, new Listener());//begin motion t.start(); } public void paintComponent(Graphics g) { g.setColor(Color.green); g.fillRect(0,0, 1250, 900);//create background g.setColor(Color.black); g.fillRect(0,425,1250,50);//create Route 1 g.fillRect(50,0,25,425);//create side road g.fillRect(225,0,25,425);//create side road g.fillRect(305,475,25,425);//create side road g.fillRect(645,475,25,425);//create side road g.fillRect(1025,0,25,425);//create side road g.fillRect(1205,0,25,900);//create side road g.setColor(Color.white); for(int x=0;x<=1250;x+=10) g.drawLine(x,438,x+5,438);//create lane 1 for(int x=0;x<=1250;x+=10) g.drawLine(x,450,x+5,450);//create lane 2 for(int x=0;x<=1250;x+=10) g.drawLine(x,462,x+5,462);//create lane 3 car1.draw(g);//put car into system } private class Listener implements ActionListener { public void actionPerformed(ActionEvent e) { car1.move();//have car drive if(car1.getX()==150) car1.changeLaneUp();//change lane up if(car1.getX()==225) { car1.turn();//car turns left car1.move();//and continues down side road } repaint(); } } } import java.awt.*; public class Car { private int dx; private int dy; private int myL; private int myW; private int myX; private int myY; // constructor public Car(int x,int y) { myL=10;//length of car myW=8;//width of cat myX=x;//x position of car myY=y;//y position of car dx = 5; // vertically dy = 12;// sideways } //modifier methods public void setX(int x) { myX = x; } public void setY(int y) { myY = y; } public void setdx(int x) { dx=x; } public void setdy(int y) { dy=y; } public void setW(int w) { myW=w; } public void setL(int l) { myL=l; } //accessor methods public int getX() { return myX; } public int getY() { return myY; } public int getL() { return myL; } public int getW() { return myW; } public int getdx() { return dx; } public int getdy() { return dy; } //instance methods public void move() { if(getL()>getW())//if pointing down route 1 setX(getX()+dx);//move in x direction else setY(getY()-dy); //if pointing down side road //move in y direction } public void changeLaneUp() { setY(getY()-dy);//change y up setX(getX()+dx);//and move forward } public void changeLaneDown() { setY(getY()+dy);//change y down setX(getX()+dx);//and move forward } public void turn() { int temp=getL();//switch length and width setL(getW());//so that the car appears to setW(temp);// be facing new direction } public void draw(Graphics myBuffer) { myBuffer.setColor(Color.red);//create red cars to correct specification myBuffer.fillRect(getX(),getY(),getL(),getW()); } }