I have these 3 classes which is supposed to work together to create a game. But I'm getting an error in one of them where it wants me to add unimplemented methods. The class which is creating the error is called Game and looks like this.
package org.game.main;
import java.awt.Graphics2D;
public class Game extends Window {
public static void main(String[] args) {
Window window = new Game();
window.run(1.0 / 60.0);
System.exit(0);
}
public Game() {
// call game constructor
super("Test Game", 640, 480);
}
public void gameStartup() {
}
public void gameUpdate(double delta) {
}
public void gameDraw(Graphics2D g) {
}
public void gameShutdown() {
}
}
It wants me to implement the method called Update() from the Window class. The Window class looks like this.
package org.game.main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import org.game.input.*;
/**
* Game that creates a window and handles input.
* #author Eric
*/
public abstract class Window extends GameLoop {
private Frame frame;
private Canvas canvas;
private BufferStrategy buffer;
private Keyboard keyboard;
private Mouse mouse;
private MouseWheel mouseWheel;
/**
* Creates a new game window.
*
* #param title title of the window.
* #param width width of the window.
* #param height height of the window.
*/
public Window(String title, int width, int height) {
/*Log.debug("Game", "Creating game " +
title + " (" + width + ", " + height + ")");*/
// create frame and canvas
frame = new Frame(title);
frame.setResizable(false);
canvas = new Canvas();
canvas.setIgnoreRepaint(true);
frame.add(canvas);
// resize canvas and make the window visible
canvas.setSize(width, height);
frame.pack();
frame.setVisible(true);
// create buffer strategy
canvas.createBufferStrategy(2);
buffer = canvas.getBufferStrategy();
// create our input classess and add them to the canvas
keyboard = new Keyboard();
mouse = new Mouse();
mouseWheel = new MouseWheel();
canvas.addKeyListener(keyboard);
canvas.addMouseListener(mouse);
canvas.addMouseMotionListener(mouse);
canvas.addMouseWheelListener(mouseWheel);
canvas.requestFocus();
}
/**
* Get the width of the window.
*
* #return the width of the window.
*/
public int getWidth()
{
return canvas.getWidth();
}
/**
* Get the height of the window.
*
* #return the height of the window.
*/
public int getHeight()
{
return canvas.getHeight();
}
/**
* Returns the title of the window.
*
* #return the title of the window.
*/
public String getTitle()
{
return frame.getTitle();
}
/**
* Returns the keyboard input manager.
* #return the keyboard.
*/
public Keyboard getKeyboard()
{
return keyboard;
}
/**
* Returns the mouse input manager.
* #return the mouse.
*/
public Mouse getMouse()
{
return mouse;
}
/**
* Returns the mouse wheel input manager.
* #return the mouse wheel.
*/
public MouseWheel getMouseWheel() {
return mouseWheel;
}
/**
* Calls gameStartup()
*/
public void startup() {
gameStartup();
}
/**
* Updates the input classes then calls gameUpdate(double).
* #param delta time difference between the last two updates.
*/
public void update(double delta) {
// call the input updates first
keyboard.update();
mouse.update();
mouseWheel.update();
// call the abstract update
gameUpdate(delta);
}
/**
* Calls gameDraw(Graphics2D) using the current Graphics2D.
*/
public void draw() {
// get the current graphics object
Graphics2D g = (Graphics2D)buffer.getDrawGraphics();
// clear the window
g.setColor(Color.BLACK);
g.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
// send the graphics object to gameDraw() for our main drawing
gameDraw(g);
// show our changes on the canvas
buffer.show();
// release the graphics resources
g.dispose();
}
/**
* Calls gameShutdown()
*/
public void shutdown() {
gameShutdown();
}
public abstract void gameStartup();
public abstract void gameUpdate(double delta);
public abstract void gameDraw(Graphics2D g);
public abstract void gameShutdown();
}
The last class is called Gameloop and looks like this.
package org.game.main;
public abstract class GameLoop {
private boolean runFlag = false;
/**
* Begin the game loop
* #param delta time between logic updates (in seconds)
*/
public void run (double delta) {
runFlag = true;
startup();
// convert the time to seconds
double nextTime = (double) System.nanoTime() / 1000000000.0;
double maxTimeDiff = 0.5;
int skippedFrames = 1;
int maxSkippedFrames = 5;
while (runFlag) {
// convert the time to seconds
double currTime = (double) System.nanoTime() / 1000000000.0;
if ((currTime - nextTime) > maxTimeDiff) nextTime = currTime;
if (currTime >= nextTime) {
// assign the time for the next update
nextTime += delta;
update();
if ((currTime < nextTime) || (skippedFrames > maxSkippedFrames)) {
draw();
skippedFrames = 1;
}
else {
skippedFrames++;
}
} else {
// calculate the time to sleep
int sleepTime = (int)(1000.0 * (nextTime - currTime));
// sanity check
if (sleepTime > 0) {
// sleep until the next update
try {
Thread.sleep(sleepTime);
}
catch(InterruptedException e) {
// do nothing
}
}
}
}
shutdown();
}
public void stop() {
runFlag = false;
}
public abstract void startup();
public abstract void shutdown();
public abstract void update();
public abstract void draw();
}
The error I'm getting in console when I run the main class looks like this.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The type Game must implement the inherited abstract method GameLoop.update()
at org.game.main.Game.update(Game.java:5)
at org.game.main.GameLoop.run(GameLoop.java:26)
at org.game.main.Game.main(Game.java:8)
I hope you can help me. I'm quite new to java.
The signature of the update method is not overriding the interface, if that's what you intended.
public void update(double delta)
You need it to match the interface
public abstract void update();
So it sounds like this simple change should help:
public abstract void update(double delta);
In GameLoop you have defined
public abstract void update();
This method must be implemented in one of the sub classes Window or Game with the same signature.
You have implement unimplemented methods of Game Window and GameLoop class
Implement abstract methods. Window class' abstract methods are following:
public abstract void gameStartup();
public abstract void gameUpdate(double delta);
public abstract void gameDraw(Graphics2D g);
public abstract void gameShutdown();
Also implement following methods of GameLoop class
public abstract void startup();
public abstract void shutdown();
public abstract void update();
public abstract void draw();
Okay i found it out with some of the help that you suggested. It was because I hadn't defined Update() in GameLoop as.
public abstract void update(double delta);
Insted of
public abstract void update();
So the method didn't get called in Window. So then it had to be called in Game. Thanks for the help, everything works as should now.
Related
I am trying to start my game from a Main Menu class that implements NiftyGUI. I am using OpenGL (LWJGL) and Java. The problem is that I am never able to get the main menu to disappear and then start the game class, which is World.java.
The following is what I would usually do when I have no main menu.
package com.dev.voxy;
import com.dev.voxy.utilities.GLScreen;
import com.dev.voxy.world.World;
public class Main extends GLScreen {
public static int WIDTH = 1280;
public static int HEIGHT = 720;
private World world;
public static void main(String[] args) {
Main main = new Main();
main.GLScreen(WIDTH, HEIGHT, false, 60, "Voxy");
}
#Override
public void init() {
world = new World();
}
#Override
public void update() {
world.update();
}
#Override
public void dispose() {
world.dispose();
}
That is my main class and extends GLScreen
import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.util.glu.GLU.gluPerspective;
public abstract class GLScreen {
protected static int SCREEN_WIDTH;
protected static int SCREEN_HEIGHT;
protected boolean FULL_SCREEN;
protected static int FPS = 60;
protected static String SCREEN_TITLE;
private static long lastFPS;
private static int lfps;
public static int fps;
public void GLScreen(int width, int height, boolean fullscreen, int sync, String title) {
this.SCREEN_HEIGHT = height;
this.SCREEN_WIDTH = width;
this.FULL_SCREEN = fullscreen;
this.FPS = sync;
this.SCREEN_TITLE = title;
InitScreen();
}
public void InitScreen() {
createWindow();
InitGL();
init();
Run();
}
void createWindow() {
try {
Display.setFullscreen(FULL_SCREEN);
Display.setTitle(SCREEN_TITLE);
DisplayMode displayMode = new DisplayMode(SCREEN_WIDTH, SCREEN_HEIGHT);
Display.setDisplayMode(displayMode);
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
}
}
void InitGL(){
glEnable(GL_TEXTURE_2D);
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glViewport(0, 0, Display.getWidth(), Display.getHeight());
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(67.0f, SCREEN_WIDTH / SCREEN_HEIGHT, 0.001f, 1000f); //TODO watch coding universe video
glMatrixMode(GL_MODELVIEW);
glEnable(GL_DEPTH_TEST);
lastFPS = getTime();
}
public abstract void init();
public abstract void update();
public static int getFPS() {
int cfps;
if (getTime() - lastFPS > 1000 && lfps != fps) {
lfps = fps;
fps = 0; //reset the FPS counter
lastFPS += 1000; //add one second
cfps = fps;
} else {
cfps = lfps;
}
fps++;
return cfps;
}
public static long getTime() {
return (Sys.getTime() * 1000) / Sys.getTimerResolution();
}
void Run(){
while(!Display.isCloseRequested()){
try{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0, 0, 0f, 0f);
glLoadIdentity();
update();
Display.update();
Display.sync(FPS);
} catch (Exception e){
e.printStackTrace();
}
}
dispose();
destroy();
}
public abstract void dispose();
public void destroy() {
Display.destroy();
System.exit(0);
}
}
And finally my World Class is below.
import com.dev.voxy.Main;
import org.lwjgl.opengl.Display;
import static org.lwjgl.opengl.GL11.glColor3f;
import static org.lwjgl.opengl.GL11.glLoadIdentity;
public class World extends WorldManager {
private Chunk chunk;
public World() {
super(Main.WIDTH, Main.HEIGHT);
init();
}
#Override
public void init() {
chunk = new Chunk(0, 0, 0);
setRenderStats(true);
}
public void update() {
input();
render();
}
public void render() {
render3D();
Translate();
chunk.render();
glLoadIdentity();
if (isRenderStats()) {
render2D();
glColor3f(1, 1, 1);
renderStats();
}
}
#Override
public void dispose() {
chunk.dispose();
Display.destroy();
System.exit(0);
}
}
The problem is that when I try and incorporate my Menu into this it never works. First I tried GameStates so that whenever the game state is GAME the nifty should no longer render but this causes the Window to close because nifty no longer keeps it open, so then I tried to have the loop be outside the MainMenu Class but that also did not work because I kept running into static/non-static errors which I could not figure out. Then my last idea was why not try and put the gameloop inside the MainMenu Class but try to stop the nifty render while I try to start the game, but that left elements of the nifty on the screen and the rest was blank and the World class did not render. The following are my current Main, MainMenu, GLScreen and MyScreenController and MainMenu.xml files The MyscreenController controls what happens when the respective buttons are pressed and the MainMenu.xml is the nifty xml file that lays out everything.
All relevant files and classes may be found at the following link, they are the current ones where I am trying to get the main menu working. The classes shown above show what I did to get ONLY the game part working in the first place, without a menu.
LINK
To sum up, I can get my game working when there is not main menu and I can get my main menu working when there is no game, I have tried as many things I can think of but after 3 days I'm simply lost and would like any suggestion/recommendation or idea. I think I just can't figure out how to manage game states and the game loop when there is a main menu and a game, I was thinking maybe if there was a way to stop nifty completely then clear the screen then set OpenGL to 3D I can get my game rendered, this is what I was trying to do near the end but could not figure it out.
Thank you.
I have a simple applet that I want to run locally yet java is blocking it.
The applet code is as such:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FollowMe extends JApplet
{
private int xCoord = 100, yCoord = 100;
/**
* init method
*/
public void init()
{
setBackground(Color.WHITE);
addMouseMotionListener(new MyMouseMotionListener());
}
/**
* paint method
*/
public void paint(Graphics g)
{
// Call the base class paint method.
super.paint(g);
// Draw the string at the current mouse location.
g.drawString("Hello", xCoord, yCoord);
}
/**
* Private inner class that handles mouse
* motion events.
*/
private class MyMouseMotionListener implements MouseMotionListener
{
/**
* mouseMoved method
*/
public void mouseMoved(MouseEvent e)
{
// Get the mouse pointer's X and Y coordinates.
xCoord = e.getX();
yCoord = e.getY();
// Force the paint method to execute.
repaint();
}
/**
* Unused mouseDragged method
*/
public void mouseDragged(MouseEvent e)
{
}
}
}
And of course I reference the class file in my HTML file.
I have gone to my JAVA security settings and added the following exception:
"file:///D:/Downloads/AppletsExamples%281%29/01%20-%20FollowMe%20Applet/FollowMe.html"
which as you can see is the path I open in firefox to access my Html file.
However, JAVA still blocks the applet. This is getting so frustrating and I couldn't find any help elsewhere.
I am getting a error that looks like this,
run:
Exception in thread "main" java.lang.ExceptionInInitializerError
at ao.Game.main(Game.java:11)
Caused by: java.lang.RuntimeException: Uncompilable source code -
ao.Panel is not abstract and does not override abstract method
keyReleased(java.awt.event.KeyEvent) in java.awt.event.KeyListener
at ao.Panel.<clinit>(Panel.java:15)
... 1 more
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)
I can't figure out what the problem with the public class is.
There are 2 separate files below.
Game.java
Panel.java
First File:
package ao;
import ao.Panel;
import javax.swing.JFrame;
public class Game {
public static void main(String[] args) {
JFrame frame = new JFrame("2D Shooter Pre-Alpha");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new Panel());
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Next File:
package ao;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
/**
*
* #author andyoppenheimer
*/
public class Panel extends JPanel implements Runnable, KeyListener {
// panel dimensions
public static final int WIDTH = 320;
public static final int HEIGHT = 240;
public static final int SCALE = 2;
// main loop
private Thread thread;
private boolean running = false;
private int fps = 60;
private long targetTime = 1000 / fps;
// drawing
private Graphics2D g;
private BufferedImage image;
public Panel() {
setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setFocusable(true);
requestFocus();
}
public void addNotify() {
super.addNotify();
if (thread == null) {
running = true;
addKeyListener(this);
thread = new Thread(this);
thread.start();
}
}
public void init() {
image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) image.getGraphics();
}
public void update() {
}
public void draw() {
g.clearRect(0, 0, WIDTH, HEIGHT);
}
public void drawToScreen() {
Graphics g2 = getGraphics();
g2.drawImage(image, 0, 0, WIDTH * SCALE, HEIGHT * SCALE, null);
g2.dispose();
}
public void run() {
init();
long start;
long elapsed;
long wait;
while (running == true) {
start = System.nanoTime();
update();
draw();
drawToScreen();
elapsed = System.nanoTime() - start;
wait = targetTime - elapsed / 1000000;
if (wait < 0) {
wait = 5;
}
try {
Thread.sleep(wait);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void KeyPressed(KeyEvent k) {
}
public void KeyReleased(KeyEvent k) {
}
public void KeyTyped(KeyEvent k) {
}
}
In java methods starts with lower case keyTyped keyReleased and keyPressed so you are not overriding KeyListener methods.
You can annotate a method with #Override
this causes a compile error if it doesn't actually override. Section 9.6.1.4 of the JLS says:
The annotation type Override supports early detection of such problems. If a method declaration is annotated with the annotation #Override, but the method does not in fact override any method declared in a superclass, a compile-time error will occur.
Your class definition will lead to possible potential bugs cause
public class Panel extends JPanel implements Runnable, KeyListener
Calling Panel it's confusing cause already exists java.awt.Panel so call it different. Implementing multiple interface like that brokes Single Responsability Principle . A possible solution is to make inner classes or anonymous classes. For sure if you don't override a method is not necessary to extends JPanel. Take care that if you use KeyListener components must be in focus and be focusable and bind it to all keys, instead you can use KeyBindings. Don't use requestFocus instead use requestFocusInWindow() if you read api it says it's discouraged.
The class implements the KeyListener interface but does not provide an implementation for the keyReleased, keyPressed and keyTyped methods specified on the interface. Instead it provides implementations for: KeyReleased, KeyPressed and KeyTyped which are not properly cased.
I am trying to push a new screen when a bitmap is "clicked" on the screen. For this I have created a Class from this post: Blackberry Clickable BitmapField whose partial code I've posted below:
public class CustomMenuButtonField extends Field{
Bitmap normal,focused;
...
protected boolean navigationClick(int status, int time)
{
// push new screen
fieldChangeNotify(0);
return true;
}
...
I want to push a new screen when the user clicks the bitmap. I have consulted this thread:
Communicating between classes, but I still can't figure out the commands to call the new screen command. The UserInterface I have so far is:
public class UserInterface extends UiApplication {
public static void main(String[] args){
UserInterface theApp = new UserInterface();
theApp.enterEventDispatcher();
}
public UserInterface() {
pushScreen(new UserInterfaceScreen());
}
}
final class UserInterfaceScreen extends MainScreen {
public UserInterfaceScreen() {
...
What would be the command to pop up the new screen, and more importantly where would I be able to work on it? I know it should probably use pushScreen() but that is not recognized in that class. Would I create a new final class NewScreenFromClick extends MainScreen? and if so how would I call it and put it in the eventDispatcher. I've been going through the blackberry site but they don't have much sample code on this issue and I am very new to Java so this is fairly confusing to me.
imageField imageField = new imageField ("",Field.FOCUSABLE,"image.png","image.png", 0x102839);
add(imageField );
FieldChangeListener listener = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if (field == imageField ) {
home home = new home();//your screen
UiApplication.getUiApplication().pushScreen(home);
}
}
};
imageField .setChangeListener(listener);
//imagefield class is given below
package com.pl.button;
import net.rim.device.api.ui.*;
import net.rim.device.api.system.*;
public class imagefield extends Field {
private String _label;
private int _labelHeight;
private int _labelWidth;
private Font _font;
private Bitmap _currentPicture;
private Bitmap _onPicture;
private Bitmap _offPicture;
int color;
public imagefield (String text, long style ,String img, String img_hvr, int color){
super(style);
_offPicture = Bitmap.getBitmapResource(img);
_onPicture = Bitmap.getBitmapResource(img_hvr);
_font = getFont();
_label = text;
_labelHeight = _onPicture.getHeight();
_labelWidth = _onPicture.getWidth();
this.color = color;
_currentPicture = _offPicture;
}
/**
* #return The text on the button
*/
String getText(){
return _label;
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#getPreferredHeight()
*/
public int getPreferredHeight(){
return _labelHeight;
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#getPreferredWidth()
*/
public int getPreferredWidth(){
return _labelWidth;
}
/**
* Field implementation. Changes the picture when focus is gained.
* #see net.rim.device.api.ui.Field#onFocus(int)
*/
protected void onFocus(int direction) {
_currentPicture = _onPicture;
invalidate();
}
/**
* Field implementation. Changes picture back when focus is lost.
* #see net.rim.device.api.ui.Field#onUnfocus()
*/
protected void onUnfocus() {
_currentPicture = _offPicture;
invalidate();
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#drawFocus(Graphics, boolean)
*/
protected void drawFocus(Graphics graphics, boolean on) {
// Do nothing
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#layout(int, int)
*/
protected void layout(int width, int height) {
setExtent(Math.min( width, getPreferredWidth()),
Math.min( height, getPreferredHeight()));
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#paint(Graphics)
*/
protected void paint(Graphics graphics){
// First draw the background colour and picture
graphics.setColor(this.color);
graphics.fillRect(0, 0, getWidth(), getHeight());
graphics.drawBitmap(0, 0, getWidth(), getHeight(), _currentPicture, 0, 0);
// Then draw the text
graphics.setColor(Color.BLACK);
graphics.setFont(_font);
graphics.drawText(_label, 4, 2,
(int)( getStyle() & DrawStyle.ELLIPSIS | DrawStyle.HALIGN_MASK ),
getWidth() - 6 );
}
/**
* Overridden so that the Event Dispatch thread can catch this event
* instead of having it be caught here..
* #see net.rim.device.api.ui.Field#navigationClick(int, int)
*/
protected boolean navigationClick(int status, int time){
fieldChangeNotify(1);
return true;
}
}
You can use:
UiApplication.getUiApplication().pushScreen(new HomeScreen());
If your application is not doing anything strange UiApplication.getUiApplication() will always return the UiApplication object for your program. This is a singleton object created for each UiApplication context.
You could also use:
UserInterface.getUiApplication().pushScreen(new HomeScreen());
If the UserInterface class is visible to the class you are working on, but this would make your code less re-usable.
I've collected some basic samples on my blog. Have a look at this page. Start at the bottom and work your way up.
Try the following code I have added UserInterfaceScreen. When UserInterfaceScreen is constructed, it adds a CustomMenuButtonField and sets a field change listener. When the button is clicked it pushes the new screen to the stack
package mypackage;
import net.rim.device.api.ui.UiApplication;
public class UserInterface extends UiApplication {
public static void main(String[] args){
UserInterface theApp = new UserInterface();
theApp.enterEventDispatcher();
}
public UserInterface() {
pushScreen(new UserInterfaceScreen());
}
}
This is the UserInterfaceScreen
package mypackage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.container.MainScreen;
public class UserInterfaceScreen extends MainScreen {
public UserInterfaceScreen() {
super();
//replace null with the image string
CustomMenuButtonField button = new CustomMenuButtonField(null, null);
button.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
UiApplication.getUiApplication().pushScreen(new MyHomeScreen());
}
});
}
}
Look the answer in the below link which I posted by me(alishaik786) :
Clickable Bitmap;
I have a question about when paint and update method is called??
i have game applet where i want to use double buffering.But i cant use it.the problem is
In my game there is a ball which is moving inside run() method.I want to know how to use double buffering to swap the offscreen image and current image.Someone plz help.
And when there is both update() and paint() method.which are called first,when and why ???
A method you can use is to add a Canvas to the applet and then create a buffer strategy for that canvas. Abstracts the code, and you may get hardware acceleration.
The code is here: http://www.gamedev.net/community/forums/topic.asp?topic_id=405663 -- extend AppletGameCore and define your own subclass that implements the required methods.
import java.awt.Canvas;
import java.awt.Graphics2D;
import java.awt.Dimension;
import java.awt.image.BufferStrategy;
import java.applet.Applet;
/**
*AppletGameCore.java
*#author David Graham
*/
public abstract class AppletGameCore extends Applet implements Runnable
{
private BufferStrategy bufferStrategy;
private Canvas drawArea;/*Drawing Canvas*/
private boolean stopped = false;/*True if the applet has been destroyed*/
private int x = 0;
public void init()
{
Thread t = new Thread(this);
drawArea = new Canvas();
setIgnoreRepaint(true);
t.start();
}
public void destroy()
{
stopped = true;
/*Allow Applet to destroy any resources used by this applet*/
super.destroy();
}
public void update()
{
if(!bufferStrategy.contentsLost())
{
//Show bufferStrategy
bufferStrategy.show();
}
}
//Return drawArea's BufferStrategy
public BufferStrategy getBufferStrategy()
{
return bufferStrategy;
}
//Create drawArea's BufferStrategies
public void createBufferStrategy(int numBuffers)
{
drawArea.createBufferStrategy(numBuffers);
}
//Subclasses should override this method to do any drawing
public abstract void draw(Graphics2D g);
public void update(Graphics2D g)
{
g.setColor(g.getBackground());
g.fillRect(0,0,getWidth(),getHeight());
}
//Update any sprites, images, or primitives
public abstract void update(long time);
public Graphics2D getGraphics()
{
return (Graphics2D)bufferStrategy.getDrawGraphics();
}
//Do not override this method
public void run()
{
drawArea.setSize(new Dimension(getWidth(),getHeight()));
add(drawArea);
createBufferStrategy(2);
bufferStrategy = drawArea.getBufferStrategy();
long startTime = System.currentTimeMillis();
long currTime = startTime;
//animation loop
while(!stopped)
{
//Get time past
long elapsedTime = System.currentTimeMillis()-currTime;
currTime += elapsedTime;
//Flip or show the back buffer
update();
//Update any sprites or other graphical objects
update(elapsedTime);
//Handle Drawing
Graphics2D g = getGraphics();
update(g);
draw(g);
//Dispose of graphics context
g.dispose();
}
}
}