I currently have a GUI program that repaints, however it does not have a Timer
implemented so it is repainting at every clock from the CPU (which is taking my CPU up to 65% usage). I've seen mention that a Timer
can solve this problem by scheduling tasks to run after however many ticks you choose. However, I'm not sure how to implement it into my program. My program currently looks similar to this:
public static void main(String[] args)
{
// create new Jframe
JFrame frame = new JFrame("Game");
frame.add(new Game());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
while (1 == 1)
{
frame.repaint();
}
}
The paint method handles various parts of the game such as movement. For example, if a forward button is clicked, the GUI will repaint with the player moved up by one. When I searched examples of a Timer
, it was used in the run()
method which I do not have in my program. Does the Timer
get implemented into the body of the class (e.g. inside the paintComponent()
method) and then ran inside main()
?
I tried using something such as this:
paintComponent()
{
// everything that it does
Timer updater = new Timer(1);
}
public static void main(String[] args)
{
// create new Jframe
JFrame frame = new JFrame("Game");
frame.add(new Game());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
while (1 == 1)
{
new Timer(1);
frame.repaint();
}
}
But this doesn't work as I believe that timers need to be ran.