Last active
December 22, 2015 19:19
-
-
Save Prince781/6518455 to your computer and use it in GitHub Desktop.
Example double-buffering using Canvas2D; excerpt from Project X.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/******************************* | |
* Example of double buffering | |
* in Canvas2D | |
********************************/ | |
import java.awt.*; | |
import java.awt.event.*; | |
import java.awt.image.*; | |
import java.util.*; | |
import javax.swing.*; | |
public class BufferingDemo extends Thread { | |
private Graphics2D g2d; //initial buffer | |
private Graphics2D b_g2d; //background graphics | |
private Canvas canvas; | |
private BufferStrategy strategy; | |
private BufferedImage background; | |
private boolean running = false; | |
private GraphicsConfiguration cfg = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration(); | |
private Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); | |
public BufferingDemo() { | |
running = true; //set the thread to on | |
start(); //inherited method for initializing thread | |
} | |
public BufferedImage createBufferedImage(final int width, final int height, final boolean alpha) { | |
return cfg.createCompatibleImage(width, height, alpha ? Transparency.TRANSLUCENT : Transparency.OPAQUE); | |
} | |
private Graphics2D getBuffer() { //return buffer for graphics | |
if (g2d == null) try { | |
g2d = (Graphics2D) strategy.getDrawGraphics(); | |
} catch (IllegalStateException e) { | |
return null; | |
} | |
return g2d; | |
} | |
public void run() { //thread process to iterate | |
b_g2d = (Graphics2D) background.getGraphics(); | |
main: while (running) { | |
gameUpdate(); | |
do { | |
Graphics2D bg = getBuffer(); //background | |
if (!running) break main; | |
render(b_g2d); //render to background graphics | |
bg.drawImage(background, 0, 0, null); | |
} while (!screenUpdate()); | |
} | |
window.dispose(); //release system resources | |
} | |
public boolean screenUpdate() { | |
g2d.dispose(); //release system resources | |
g2d = null; | |
try { | |
strategy.show(); | |
Toolkit.getDefaultToolkit().sync(); | |
return (!strategy.contentsLost()); | |
} catch (NullPointerException e) { | |
return true; | |
} catch (IllegalStateException e) { | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment