I have an assignment about making a car simulation program in Java. I'm currently having trouble with moving the car in the map. Here's the code of the Map (main) class
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import project.Car;
public class Map extends JPanel {
public static void main(String[] args)
{
JFrame f = new JFrame();
f.setSize(800, 450);
f.add(new Map());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
Car carA = new Car();
Car carB = new Car();
/*
int rX = randX();
carA.positionX = carA.setPositionX(rX);
System.out.println(carA.getPositionX());
*/
}
public static int randX()
{
Random rnX = new Random();
int randomX = rnX.nextInt((40 - 0) + 1) + 0;
if (randomX >= 0 && randomX <= 4 || randomX == 20 && randomX <= 24 || randomX >= 25)
{
randX();
}
return randomX;
}
public static int randY()
{
Random rnY = new Random();
int randomY = rnY.nextInt((55 - 15) + 1) + 15;
if (randomY >= 0 && randomY <= 4 || randomY >= 25 && randomY <= 29 || randomY >= 30)
{
randY();
}
return randomY;
}
//paint a = new paint();
public void paint(Graphics g)
{
g.drawRect (0 , 0, 500,200); //
g.drawRect (20, 25, 450,150); // The road
g.drawRect (40, 50, 400,100); //
g.drawRect (10 , 10, 8,8); //One of the car's initialization
}
}
And here's the Car class
import java.awt.Graphics;
import java.awt.Toolkit;
import java.util.Random;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.util.Timer;
import java.util.TimerTask;
public class Car extends JPanel
{
int positionX = 0;
int positionY = 0;
int weight = 0;
//int lane = 0;
public int getPositionX()
{
return positionX;
}
public int setPositionX(int newPosX)
{
positionX = newPosX;
return positionX;
}
public int getPositionY()
{
return positionY;
}
public int setPositionY(int newPosY)
{
positionY = newPosY;
return positionY;
}
public int Accelerate()
{
Toolkit toolkit = Toolkit.getDefaultToolkit();
Timer timer = new Timer();
timer.schedule(new RemindTask(), 0, //initial delay
1 * 1000); //subsequent rate
//schedule(TimerTask task, long delay);
return positionX;
}
class RemindTask extends TimerTask
{
//int numWarningBeeps = 3;
public void run()
{
if(positionX <= 450 && positionY <= 23)
{
positionX += 1;
}
else if(positionX == 450 && positionY <= 23)
{
positionY+= 1;
}
else if(positionY <= 150 && positionX >= 15)
{
positionX -= 1;
}
else if(positionY == 150 && positionX == 23)
{
positionY -= 1;
}
}
}
public static int main(int[] args)
{
return 0;
}
}
As it seems, I don't know how to apply the timer I've made, nor I know whether it works or not.. Please give me some guidance on how to apply timer so that the car can move around in the designated area..