Self written timer with System.nanoTime()
I'm just trying to make a rectangle move over the horizontal direction. Below you can find the code I have written, but it doesn't work when I click drop-button.
I don't understand why it doesn't work. Could somebody push me in the right direction?
Thank you in advance!
public class SimulationREAL extends JPanel implements ActionListener
private JButton dropknop;
private boolean drop = false;
public boolean timer = false;
private int Xpos;
long time0 = System.nanoTime();
double time = 0;
double lastTime = 0;
double dt = 0;
double velocity = 2; // define the initial velocity of the object
dropknop = new JButton("DROP");
time = (System.nanoTime() - time0)/1E9; // time in seconds from the beginning
dt = time - lastTime; //time of last loop
lastTime = time;
Xpos += velocity * dt;
public void paintComponent(Graphics g)
g.drawRect(Xpos, 0, 20, 20);
public void actionPerformed(ActionEvent e)
if(e.getSource() == dropknop)
this.drop = true;
Re: Self written timer with System.nanoTime()
Try and insert some debug printing before and after your drop while loop. And try to explain your idea behind the flow of the program execution. Also what is the expected behavior of your code when the button is pressed, how is the while loop being reached.