1

I am trying to make a game in java and have encountered a problem. When my program repaints my JFrame it takes a lot of power from my CPU, I was wondering if there was some glaring mistake I'm overlooking or a way to decrease the CPU usage.

Frame.java

public class Frame extends JFrame {
    JFrame frame;
    public static Panel panel;

    public void makeFrame() {
        frame = new JFrame("Game");
        panel = new Panel();
        panel.init();

        frame.setSize(1000, 1000);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setVisible(true);
        frame.add(panel);
     }
}

GameLoop.java

public class GameLoop {
//render gets called 30 times per second
    private void render() {
        Frame.panel.repaint();
    }
}

Panel.java

public class Panel extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        mvmt.drawCha(g2d);   //mvmt is an instance of Movement
    }
}

Movement.java

public class Movement {
    public void drawCha(Graphics2D g2d) {
        g2d.drawImage(charImg, x , y, x + 40 , y + 40, 0, 0, 17, 28, null);
    }
}

Thanks in advance for any help!

1 Answers1

1

You say you already limit the loop to 30 ticks per second, than I don't think your repainting is the cause. Do you still have a lot of cpu usage when not repainting?

If so, I think your cpu goes to your loop when it's doing nothing between the ticks in, thus draining you cpu. This all I'm assuming that you are using a thread and not doing anything with the spare time of the thread.

Voltboyy
  • 129
  • 1
  • 8
  • The program uses about ~60% of the cpu with the repaint method and ~30% without it. I would like to cut down on the cpu usage of the loop but I thought I would tackle one problem at a time. Also, the method I used for the loop uses `System.nanotime()` – Charlie Landrigan Oct 27 '16 at 00:23
  • @CharlieLandrigan The usage you describe sounds normal for a standard or lower end CPU. One way to decrease usage would to redraw the changed/updated portion of the screen only (rather than the whole screen each time), but it does involve some extra logic to track what to repaint. – sorifiend Oct 27 '16 at 01:11