Hi I am reading the book "Programming Video Games for the Evil Genius" by Ian Cinnamon. In one of the projects he explains how to create some animation for a racing game. I wrote a simple code below (removing "almost" everything unnecessary). But the result is the same: the flickering.
My question is how, by using that same code (with little modifications obviously) can I make it stop flickering? My point is not to find another way around (modifying the whole code) because I am already able to create an entire game using JLabel, ImageIcon classes & spritesheets image files. My point is to solve the flickering problem without removing those shapes [Rectangle (fillRect & if possible drawImage)].
By the way if this is not possible "Why would you do that!?" or "It's impossible" are also good answers. (let's try not to use them!)
Thank You!
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class Race extends JFrame {
public static void main(String[] args){
new Race();
}
private Rectangle r1 = new Rectangle(0,0,800,100);
private Rectangle r2 = new Rectangle(0,100,100,400);
Image img = null;
public Race(){
super("Some Title");
setVisible(true);
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try{
URL url= this.getClass().getResource("someImage.png");
img =Toolkit.getDefaultToolkit().getImage(url);
}catch(Exception e){}
Race.GameLoop gameHeart = new Race.GameLoop();
gameHeart.run();
}
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.GREEN);
g.fillRect(r1.x, r1.y, r1.width, r1.height);
g.setColor(Color.RED);
g.fillRect(r2.x, r2.y, r2.width, r2.height);
g.drawImage(img, r2.x, r2.y, r2.width, r2.height, this);
try {
Thread.sleep(75);
} catch (InterruptedException ex) {}
repaint();
}
public class GameLoop extends Thread {
public void run(){
while(true){
//game animations and logic
//even if I put repaint() here it still flicker
}
}
}
}