All pastes #408444 Raw Edit

Something

public text v1 · immutable
#408444 ·published 2007-03-24 20:57 UTC
rendered paste body
import java.awt.Canvas;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Dimension;
import java.awt.image.BufferStrategy;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Game extends Canvas
{
	private JFrame frame;
	private int width;
	private int height;
	private JPanel panel;
	private BufferStrategy strategy;
	private boolean gameRunning;
	private long lastLoopTime;
	private int delay;

	public Game(String title, int width, int height, boolean fullScreen, int maxFPS)
	{
		frame = new JFrame(title);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		this.width = width;
		this.height = height;

		delay = 1000 / maxFPS;

		panel = (JPanel)frame.getContentPane();
		panel.setPreferredSize(new Dimension(width, height));
		panel.setLayout(null);

		setBounds(0, 0, width, height);
		panel.add(this);
		
		setIgnoreRepaint(true);

		if (fullScreen) {
			GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
			GraphicsDevice gd = ge.getDefaultScreenDevice();
			if (gd.isFullScreenSupported()) {
				System.out.println("Entering full-screen mode...");
				gd.setFullScreenWindow(frame);
			}
		}

		frame.pack();
		frame.setResizable(false);
		frame.setVisible(true);

		createBufferStrategy(2);
		strategy = getBufferStrategy();
	}

	public void start()
	{
		gameRunning = true;
		lastLoopTime = System.currentTimeMillis();

		while (gameRunning) {
			long now = System.currentTimeMillis();
			long delta = now - lastLoopTime;
			lastLoopTime = now;

			Graphics2D g = (Graphics2D)strategy.getDrawGraphics();

			// draw
			
			g.dispose();
			strategy.show();

			if (delta < delay) {
				int rest = (int)(delay - delta);
				try {
					Thread.sleep(rest);
				}
				catch (InterruptedException e) {
				}
			}
		}
	}
}