I'm trying to learn how to create a game loop with java and draw a new screen a certain amount of times per second. The game loop is working fine but when I try to call the paint method with repaint() the paint method is not called. Here is my code:
import javax.swing.JButton;
import javax.swing.JComponent;
import java.awt.Graphics;
import javax.swing.JFrame;
import java.awt.image.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class mainFrame extends Thread{
static boolean gameIsRunning = false;
MyCanvas2 myCanvas2 = new MyCanvas2();
static final int TARGET_FPS = 1;
static int x = 10;
static int y = 10;
static long startTime = 0;
static long elapsedTime = 0;
static long waitTime = 0;
public void createFrame(){
JFrame window = new JFrame("Out from Eden");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 700, 500);
window.setVisible(true);
gameIsRunning = true;
gameStart();
}
public void setGame(boolean game){
gameIsRunning = game;
}
public void gameStart(){
(new Thread(new mainFrame())).start();
}
public void run(){
while(gameIsRunning == true){
startTime = System.nanoTime();
myCanvas2.updateGame();
myCanvas2.renderGame();
elapsedTime = System.nanoTime() - startTime;
waitTime = (TARGET_FPS*10) - (elapsedTime / 1000000);
if (waitTime < 0) {
waitTime = 5;
}
try {
Thread.sleep(waitTime);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class MyCanvas2 extends JPanel{
private static int x = 100;
private static int y = 100;
static int i =0;
public void updateGame(){
}
public void renderGame(){
repaint();
System.out.println("Hello");
}
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g.setColor(Color.blue);
g2.drawString("Test", x,y);
System.out.println("Goodbye");
}
}
Hello is printed out many times but Goodbye is never called, this leads me to believe that the paint method is never called. Why won't the repaint method update my paint method?