import java.awt.AWTEvent;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Transparency;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Example extends Canvas {
static final int KEYS = 65536;
int font_height = 10;
int width_in_chars = 80;
int height_in_chars = 40;
BufferStrategy strategy;
BufferedImage buffer;
boolean keys[];
public Example() {
Font font = new Font(Font.MONOSPACED, Font.PLAIN, font_height);
keys = new boolean[KEYS];
int win_width = width_in_chars * getFontMetrics(font).charWidth(' ');
int win_height = height_in_chars * font_height;
JFrame f = new JFrame();
JPanel p = (JPanel) f.getContentPane();
p.setPreferredSize(new Dimension(win_width, win_width));
p.setLayout(null);
setBounds(0, 0, win_width, win_height);
p.add(this);
f.pack();
f.setResizable(false);
f.setTitle("Example Project");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.setFont(font);
f.setLocationRelativeTo(null);
createBufferStrategy(2);
strategy = getBufferStrategy();
GraphicsConfiguration gc = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
buffer = gc.createCompatibleImage(win_width, win_height,
Transparency.OPAQUE);
setIgnoreRepaint(true);
enableEvents(AWTEvent.KEY_EVENT_MASK);
}
void mainLoop() {
while (!keys[KeyEvent.VK_ESCAPE]) {
try {
Thread.sleep(10);
} catch (InterruptedException e) { }
// draw on buffer
buffer.getGraphics().drawLine(0, 0, 100, 100);
// blit buffer to screen
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
paint(g);
g.dispose();
strategy.show();
}
}
@Override
public void paint(Graphics g) {
g.drawImage(buffer, 0, 0, this);
}
@Override
public void processKeyEvent(KeyEvent e) {
keys[e.getKeyCode()] = e.getID() == KeyEvent.KEY_PRESSED;
}
public static void main(String[] args) {
new Example().mainLoop();
}
}