Note that there are some explanatory texts on larger screens.

plurals
  1. POSwing timer - time fluctuating
    primarykey
    data
    text
    <p>I am using a Swing Timer in my game but when the game is running it appears to have moments when it runs smoothly and moments when it slows down. </p> <p>Why is the time fluctuating? </p> <p>And how do I fix it?</p> <pre><code>import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class Main extends JFrame { public Main() { super("JFrame"); // you can set the content pane of the frame // to your custom class. setContentPane(new ImagePanel()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(800, 400); setResizable(false); setVisible(true); } public static void main(String[] args) { // TODO Auto-generated method stub new Main(); } class ImagePanel extends JPanel { Timer movementtimer; int x, y; public ImagePanel() { x = 0; y = 0; movementtimer = new Timer(12, new ActionListener() { public void actionPerformed(ActionEvent e) { long timstarted = System.currentTimeMillis(); moveImage(); repaint(); long timefinished = System.currentTimeMillis() - timstarted; System.out.println(timefinished + " to run"); }; }); movementtimer.start(); } public void moveImage() { x++; y++; if (x &gt; 800) { x = 0; } if (y &gt; 400) { y = 0; } } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.RED); g.fillRect(0, 0, 800, 400); g.setColor(Color.BLUE); g.fillRect(x, y, 50, 50); } } } </code></pre> <p>Here is an example of my code. In my actual program I am drawing Images and not just a rectangle. There is also a lot of collision detection and other small calculations happening.</p> <p>Also, here is a link to the Jar file for the game so you can run it and (hopefull) see what I mean. <a href="http://dl.dropbox.com/u/8724803/Get%20To%20The%20Chopper%201.3.jar" rel="nofollow">http://dl.dropbox.com/u/8724803/Get%20To%20The%20Chopper%201.3.jar</a></p> <p>Thanks</p> <p>Tom</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload