Skip to content

Instantly share code, notes, and snippets.

@tuttlem
Created March 19, 2017 08:17
Show Gist options
  • Save tuttlem/a999dbd80ed047aed056d6125c3299a3 to your computer and use it in GitHub Desktop.
Save tuttlem/a999dbd80ed047aed056d6125c3299a3 to your computer and use it in GitHub Desktop.
Basic Rendering Code
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.image.BufferStrategy;
import java.util.Timer;
import java.util.TimerTask;
public class DoubleBufferDemo extends Canvas {
static {
System.setProperty("sun.java2d.trace", "timestamp,log,count");
System.setProperty("sun.java2d.transaccel", "True");
System.setProperty("sun.java2d.opengl", "True");
// System.setProperty("sun.java2d.d3d", "false"); //default on windows
// System.setProperty("sun.java2d.ddforcevram", "true");
}
private BufferStrategy strategy;
private final Timer timer;
private TimerTask renderTask;
public DoubleBufferDemo() {
this.setIgnoreRepaint(true);
timer = new Timer(); // used for the render thread
}
public void render() {
Graphics2D bkG = (Graphics2D) strategy.getDrawGraphics();
bkG.setColor(Color.BLACK);
bkG.fillRect(0, 0, getWidth(), getHeight());
// TODO: Do your rendering here
bkG.dispose();
strategy.show();
Toolkit.getDefaultToolkit().sync();
}
public void setup() {
this.createBufferStrategy(2);
strategy = this.getBufferStrategy();
start();
}
public void start() {
if (renderTask != null) {
renderTask.cancel();
}
renderTask = new TimerTask() {
long lasttime = System.currentTimeMillis();
@Override
public void run() {
long time = System.currentTimeMillis();
double dt = (time - lasttime) * 0.001;
lasttime = time;
render();
}
};
timer.schedule(renderTask, 0, 16);
}
protected void stop() {
renderTask.cancel();
}
public static void main(String[] args) {
final Frame frame = new Frame("Rendering Demo");
frame.setLayout(new BorderLayout());
final DoubleBufferDemo canvas = new DoubleBufferDemo();
frame.add(canvas);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas.setup();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment