These are the methods I use, it will run either as an applet or a standalone application.
If this isn’t a good way to do it, hopefully, someone else will offer improvements.
public class GameApplet extends Applet {
private static JFrame parentFrame=null;
private static boolean blnApplet = false;
private static int frameWidth;
private static int frameHeight;
public GameApplet() {
super();
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
enableEvents(AWTEvent.KEY_EVENT_MASK);
blnApplet = true;
}
public GameApplet(JFrame f) {
this();
parentFrame = f;
initialized = false;
blnApplet = false;
}
public void init() {
blnApplet = true;
}
public void destroy() {
}
public void reset() {
...
Initialize game objects here, load images, etc.
...
initialized = true;
}
public void start() {
new Thread() {
public void run() {
render();
...
game loop goes here
...
if (!blnApplet) {
System.exit(0);
}
}
}.start();
}
public void stop() {
}
public void render() {
if (initialized) {
...
draw on gDisplay here
...
Graphics g;
try {
g = this.getGraphics();
if (g != null) {
g.drawImage(imgDisplay, 0, 0, null);
g.dispose();
}
} catch (Exception e) {
}
}
}
public void update(Graphics g) {
paint(g);
}
public void addNotify() {
super.addNotify();
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
DisplayMode displayMode = device.getDisplayMode();
frameWidth = displayMode.getWidth();
frameHeight = displayMode.getHeight();
frameWidth = 800;
frameHeight = 600;
if (!blnApplet && parentFrame != null) {
parentFrame.setSize(parentFrame.getInsets().left + parentFrame.getInsets().right + frameWidth, parentFrame.getInsets().top + parentFrame.getInsets().bottom + frameHeight);
}
imgDisplay = createImage(frameWidth, frameHeight);
gDisplay = imgDisplay.getGraphics();
reset();
}
public static void main(String[] args) {
GameFrame frame = new GameFrame(gameName);
GameApplet game = new GameApplet(frame);
frame.add("Center", game);
frame.setUndecorated(true);
frame.setIgnoreRepaint(true);
frame.setVisible(true);
game.start();
}
}
public class GameFrame extends JFrame {
public GameFrame(String str) {
super (str);
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
}
protected void processEvent(AWTEvent evt) {
switch (evt.getID()) {
case WindowEvent.WINDOW_CLOSING:
dispose();
System.exit(0);
default:
super.processEvent(evt);
}
}
}