Thread: Repaint problem
View Single Post
  #2 (permalink)  
Old 02-16-2008, 10:12 PM
Bluefox815 Bluefox815 is offline
Member
 
Join Date: Feb 2008
Location: Oregon, USA
Posts: 24
Bluefox815 is on a distinguished road
Send a message via MSN to Bluefox815
Here is a sample layout for repainting constantly to show movement
Code:
import java.awt.*; public class Sample implements Runnable { Thread t; public void init() { t = new Thread(this); t.start(); } public void run() { while (true) { repaint(); try { t.sleep(30); } catch (InterruptedException e) { } } } public void paint(Graphics g) { // whatever you need to paint } }
This will repeatedly repaint BUT there is an annoying flicker that comes with it. You could create a "double buffer" to fix that. (this example is for applets only)
Code:
import java.applet.Applet; import java.awt.*; public class Sample extends Applet implements Runnable { Thread t; Image img; Graphics imageBuffer; public void init() { t = new Thread(this); t.start(); // the getSize() call is the ONLY reason this is meant specifically for // applets, because I don't know how to work around them. img = createImage(getSize().width, getSize().height); imageBuffer = img.getGraphics(); } public void run() { while (true) { repaint(); try { t.sleep(30); } catch (InterruptedException e) { } } } public void paint(Graphics g) { // the follow two lines are required imageBuffer.setColor(Color.white); // sets background color imageBuffer.fillRect(0, 0, getSize().width, getSize().height); // example of how to use imageBuffer imageBuffer.setColor(Color.black); imageBuffer.drawRect(0, 0, getSize().width - 1, getSize().height - 1); imageBuffer.drawString("Hello World!", 5, 15); g.drawImage(img); // NOTE: We draw the Image, not the Graphics imageBuffer } // IMPORTANT public void update(Graphics g) { paint(g); } }
If you know how big your Canvas is, then you can replace getSize().width or height with the width and height of your Canvas.

Credit: GameDev.net - Java Game Programming Part II: Making a Simple Game

Last edited by Bluefox815 : 02-16-2008 at 10:15 PM.
Reply With Quote