FidgetyTheGamer
FidgetyTheGamer

Reputation: 47

Why do my java graphics lag so much?

I know there are already many questions about slow java graphics, but none of them have solved my problem. The lag in my program seems very unnatrual, and has no explanation as far as I can tell.

I am creating a 2D game, and it has terrible lag. At first I thought it was from all the graphics being drawn in the game, so I did many things to try and improve performance, but none of them changed anything.

To make sure it was the game that was causing lag, I made a very simple (badly written) program that just moves a square across the screen.

 import java.awt.Graphics;

 import javax.swing.JFrame;
 import javax.swing.JPanel;


public class Main extends JPanel{

static Main main = new Main();

int x;
int y;

public static void main(String[]args){
    JFrame frame = new JFrame("Test");
    frame.setSize(1920, 1080);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(main);
    frame.setVisible(true);

    while(true){
        main.update();
        main.repaint();

        try {
            Thread.sleep(1000 / 60);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

public void update(){
    x++;
    y++;
}

public void paint(Graphics g){
    super.paint(g);
    g.fillRect(x, y, 100, 100);
}

}

To my suprise, this simple program lags very badly too! I have been coding the game on linux (ubuntu GNOME 14.10), but I have run it on my Windows 7 partition as well, and it doesn't change the performance. I have also updated all my graphics drivers. My computer can also run other java programs such as Minecraft with no lag at all. I even tried importing the project file for this tutorial into eclipse and running it and it ran fine: https://www.youtube.com/watch?v=ar0hTsb9sxM

Why is this happening, and how can I fix it?

Upvotes: 2

Views: 4440

Answers (1)

codedcosmos
codedcosmos

Reputation: 95

I put Toolkit.getDefaultToolkit().sync(); in my render method which appears to fix it. However you should put a If os is linux before that.

Upvotes: 7

Related Questions