Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Converting application to applet in eclipse

  1. #1
    Member
    Join Date
    Oct 2011
    Posts
    40
    My Mood
    Stressed
    Thanks
    2
    Thanked 1 Time in 1 Post

    Question Converting application to applet in eclipse

    Hi everyone. This is my first time attempting to port a java application to an applet and I am pretty lost on what to do. I wrote it in full in eclipse and it runs fine as a jar but I'd like to be able to embed it on my website.
    I'm ashamed to say but for some reason I have a lot of trouble following tutorials and examples and applying them to my own situations. I've looked at a lot of them so far and all I have been able to gather is that I need a class that extends Applet. I have a class that extends JFrame right now so I was just changing that to applet which obviously hasn't done anything for me. This is a full screen exclusive mode game, if that matters. I will post the frame class here and the class with the main method. I apologize, they are very long, but I have no concept of what's relevant for changing to get the applet working. The game was written for a school assignment but they haven't taught us applets, I am doing that on my own, this is not homework.
    Thank you!

    package zombieCity;
     
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.GraphicsDevice;
    import java.awt.GraphicsEnvironment;
    import java.awt.Window;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    import java.awt.image.BufferStrategy;
    import java.text.DecimalFormat;
     
    import javax.swing.JFrame;
     
    public abstract class Frame extends JFrame implements Runnable {
     
    	private static final long serialVersionUID = 6738664350623011520L;
    	private static long SCORE_TIMER = 1000000000L;
    	private static final int NO_DELAYS_PER_YIELD = 16;
    	/*
    	 * Number of frames with a delay of 0 ms before the animation thread yields
    	 * to other running threads.
    	 */
    	private int MAX_FRAME_SKIPS = 5; 
    	private int NUM_FPS = 10;// number of FPS values stored to get an average
    	protected int pWidth; // screen dimensions
    	protected int pHeight;
    	private Thread animator; // the thread that performs the animation
    	protected boolean running = false; // used to stop the animation thread
    	protected long period; // period between drawing in _nanosecs_
    	protected boolean isPaused = false; // pausing game indicator
    	private long statsInterval = 0L; // in ns
    	private long prevStatsTime;
    	private long totalElapsedTime = 0L;
    	private boolean finishedOff = false;
    	private long gameStartTime;
    	private int timeSpentInGame = 0; // in seconds
    	protected long currentStartTime;
    	protected int currentGameTime = 0;
    	private long frameCount = 0;
    	private double fpsStore[];
    	private long statsCount = 0;
    	protected double averageFPS = 0.0;
    	private long framesSkipped = 0L;
    	private long totalFramesSkipped = 0L;
    	private double upsStore[];
    	private DecimalFormat df = new DecimalFormat("0.##"); // 2 dp
    	protected double averageUPS = 0.0;
    	protected boolean gameOver = false;
    	private GraphicsDevice gd;
    	private Graphics gScr;
    	private BufferStrategy bufferStrategy;
     
     
    	public Frame(long period) {
    		this.period = period;
    		initFullScreen();
    		simpleInitialize();
    		addMouseListener(new MouseAdapter() {
    			public void mousePressed(MouseEvent e) {
    				mousePress(e.getX(), e.getY());
    			}
    		});
     
    		addMouseMotionListener(new MouseMotionAdapter() {
    			public void mouseMoved(MouseEvent e) {
    				mouseMove(e.getX(), e.getY());
    			}
    		});
     
    		addKeyListener(new KeyAdapter() {
    			// listen for esc on the canvas to exit game
    			public void keyPressed(KeyEvent e) {
    				int keyCode = e.getKeyCode();
    				if (keyCode == KeyEvent.VK_ESCAPE) {
    					running = false;
    				} 
    				else if (keyCode == KeyEvent.VK_SPACE)
    					simpleRestart();
    				else
    					keyPress(keyCode); // if not exiting game, process request
    			}
    			public void keyReleased(KeyEvent e) {
    				int keyCode = e.getKeyCode();
    				keyRelease(keyCode);
    			}
    		});
     
     
    		// Initialize timing elements
    		fpsStore = new double[NUM_FPS];
    		upsStore = new double[NUM_FPS];
    		for (int i = 0; i < NUM_FPS; i++) {
    			fpsStore[i] = 0.0;
    			upsStore[i] = 0.0;
    		}
     
    		gameStart();
     
    	}// end constructor
     
    	private void initFullScreen() {
    		GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    		gd = ge.getDefaultScreenDevice();
    		setUndecorated(true); 
    		setIgnoreRepaint(true);
    		setResizable(false);
    		if (!gd.isFullScreenSupported()) {
    			System.out.println("Full-screen exclusive mode not supported");
    			System.exit(0);
    			}// end if
    		gd.setFullScreenWindow(this); 
    		pWidth = getBounds().width;
    		pHeight = getBounds().height;
    		setBufferStrategy();
    	} // end of initFullScreen()
     
    	private void setBufferStrategy() {
    		createBufferStrategy(2);
    		bufferStrategy = getBufferStrategy();
    	} // end of setBufferStrategy()
     
    	/**
    	 * Starts the animation loop
    	 */
    	private void gameStart()
    	// Initialize and start the thread
    	{
    		if (animator == null || !running) {
    			animator = new Thread(this);
    			animator.start();
    		}
    	} 
     
    	public void resumeGame() {
    		isPaused = false;
    	}
     
    	public void pauseGame() {
    		isPaused = true;
    	}
     
    	public void stopGame() {
    		running = false;
    	}
     
    	public void run()
    	/* The frames of the animation are drawn inside the while loop. */
    	{
    		long beforeTime, afterTime, timeDiff, sleepTime;
    		long overSleepTime = 0L;
    		int noDelays = 0;
    		long excess = 0L;
     
    		gameStartTime = System.nanoTime();
    		prevStatsTime = gameStartTime;
    		beforeTime = gameStartTime;
     
    		currentStartTime = System.nanoTime();
     
    		running = true;
     
    		while (running) {
    			gameUpdate();
    			screenUpdate();
     
    			afterTime = System.nanoTime();
    			timeDiff = afterTime - beforeTime;
    			sleepTime = (period - timeDiff) - overSleepTime;
     
    			if (sleepTime > 0) { // some time left in this cycle
    				try {
    					Thread.sleep(sleepTime / 1000000L); // nano -> ms
    				} catch (InterruptedException ex) {
    				}
    				overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
    			} else { // sleepTime <= 0; the frame took longer than the period
    				excess -= sleepTime; // store excess time value
    				overSleepTime = 0L;
     
    				if (++noDelays >= NO_DELAYS_PER_YIELD) {
    					Thread.yield(); // give another thread a chance to run
    					noDelays = 0;
    				}
    			}
     
    			beforeTime = System.nanoTime();
     
    			/*
    			 * If frame animation is taking too long, update the game state
    			 * without rendering it, to get the updates/sec nearer to the
    			 * required FPS.
    			 */
    			int skips = 0;
    			while ((excess > period) && (skips < MAX_FRAME_SKIPS)) {
    				excess -= period;
    				gameUpdate(); // update state but don't render
    				skips++;
    			}
    			framesSkipped += skips;
    			storeStats();
    		}
    		System.exit(0); // so window disappears
    	} // end of run()
     
    	/**
    	 * Renders to the backbuffer
    	 */
    	private void gameRender(Graphics gScr) {
    		// clear the background
    		gScr.setColor(Color.black);
    		gScr.fillRect(0, 0, pWidth, pHeight);
     
    		simpleRender(gScr);
     
    		if (gameOver)
    			gameOverMessage(gScr);
    	} // end of gameRender()
     
    	private void screenUpdate() {
    		// use active rendering
    		try {
    			gScr = bufferStrategy.getDrawGraphics();
    			gameRender(gScr);
    			gScr.dispose();
    			if (!bufferStrategy.contentsLost())
    				bufferStrategy.show();
    			else
    				System.out.println("Contents Lost");
    		} catch (Exception e) {
    			e.printStackTrace();
    			running = false;
    		}
    	} // end of screenUpdate()
     
    	/**
    	 * Should be update the game state
    	 */
    	private void gameUpdate() {
    		if (!isPaused && !gameOver)
    			simpleUpdate();
     
    	} // end of gameUpdate()
     
    	private void storeStats()
    	/*
    	 * The statistics: - the summed periods for all the iterations in this
    	 * interval (period is the amount of time a single frame iteration should
    	 * take), the actual elapsed time in this interval, the error between these
    	 * two numbers;
    	 * 
    	 * - the total frame count, which is the total number of calls to run();
    	 * 
    	 * - the frames skipped in this interval, the total number of frames
    	 * skipped. A frame skip is a game update without a corresponding render;
    	 * 
    	 * - the FPS (frames/sec) and UPS (updates/sec) for this interval, the
    	 * average FPS & UPS over the last NUM_FPSs intervals.
    	 * 
    	 * The data is collected every MAX_STATS_INTERVAL (1 sec).
    	 */
    	{
    		frameCount++;
    		statsInterval += period;
     
    		if (statsInterval >= SCORE_TIMER) {
    			long timeNow = System.nanoTime();
    			timeSpentInGame = (int) ((timeNow - gameStartTime) / 1000000000L); // ns --> secs
    			if(!gameOver)
    				currentGameTime = (int) ((timeNow - currentStartTime) / 1000000000L);
     
    			long realElapsedTime = timeNow - prevStatsTime; // time since last
    			// stats collection
    			totalElapsedTime += realElapsedTime;
     
     
    			totalFramesSkipped += framesSkipped;
     
    			double actualFPS = 0; // calculate the latest FPS and UPS
    			double actualUPS = 0;
    			if (totalElapsedTime > 0) {
    				actualFPS = (((double) frameCount / totalElapsedTime) * 1000000000L);
    				actualUPS = (((double) (frameCount + totalFramesSkipped) / totalElapsedTime) * 1000000000L);
    			}
     
    			// store the latest FPS and UPS
    			fpsStore[(int) statsCount % NUM_FPS] = actualFPS;
    			upsStore[(int) statsCount % NUM_FPS] = actualUPS;
    			statsCount = statsCount + 1;
     
    			double totalFPS = 0.0; // total the stored FPSs and UPSs
    			double totalUPS = 0.0;
    			for (int i = 0; i < NUM_FPS; i++) {
    				totalFPS += fpsStore[i];
    				totalUPS += upsStore[i];
    			}
     
    			if (statsCount < NUM_FPS) { // obtain the average FPS and UPS
    				averageFPS = totalFPS / statsCount;
    				averageUPS = totalUPS / statsCount;
    			} else {
    				averageFPS = totalFPS / NUM_FPS;
    				averageUPS = totalUPS / NUM_FPS;
    			}
    			framesSkipped = 0;
    			prevStatsTime = timeNow;
    			statsInterval = 0L; // reset
    		}
    	} // end of storeStats()
     
    	private void readyForTermination() {
    		// for shutdown tasks
    		// a shutdown may not only come from the program
    		Runtime.getRuntime().addShutdownHook(new Thread() {
    			public void run() {
    				running = false;
    				finishOff();
    			}
    		});
    	} // end of readyForTermination()
    	private void finishOff()
    	/*
    	 * Tasks to do before terminating. Called at end of run() and via the
    	 * shutdown hook in readyForTermination().
    	 * 
    	 * The call at the end of run() is not really necessary, but included for
    	 * safety. The flag stops the code being called twice.
    	 */
    	{ // System.out.println("finishOff");
    		if (!finishedOff) {
    			finishedOff = true;
    			printStats();
    			restoreScreen();
    			System.exit(0);
    		}
    	} // end of finishedOff()
     
     
    	private void printStats() {
    		System.out.println("Frame Count/Loss: " + frameCount + " / "
    				+ totalFramesSkipped);
    		System.out.println("Average FPS: " + df.format(averageFPS));
    		System.out.println("Average UPS: " + df.format(averageUPS));
    		System.out.println("Time Spent: " + timeSpentInGame + " secs");
    	} // end of printStats()
     
    	private void restoreScreen()
    	/*
    	 * Switch off full screen mode. This also resets the display mode if it's
    	 * been changed.
    	 */
    	{
    		Window w = gd.getFullScreenWindow();
    		if (w != null)
    			w.dispose();
    		gd.setFullScreenWindow(null);
    	} // end of restoreScreen()
     
    	protected abstract void simpleRender(Graphics g);
    	protected abstract void gameOverMessage(Graphics g);
    	protected abstract void simpleUpdate();
    	protected abstract void mousePress(int x, int y);
    	protected abstract void mouseMove(int x, int y);	
    	protected abstract void keyPress(int keyCode);
    	protected abstract void keyRelease(int keyCode);
    	protected abstract void simpleInitialize();	
    	protected abstract void simpleRestart();
    }

    package zombieCity;
     
    /**
     * Zombie City is based on a gun shop owner who finds himself stranded in the middle
     * of a zombie infested city at night. If he can survive until the sun comes up, the
     * zombies will go back to their graves. In the mean time, the evil corporation who
     * created the zombie outbreak is sending in airborne drones to keep the zombies alive.
     * You have a limited supply of ammunition.
     * 
     * Kill enough of the drones, and you may just survive!
     * 
     * controls:
     * move left: a, or left arrow
     * move right: d, or right arrow
     * shoot: left mouse click to shoot towards spot clicked. Bullet speed varies based 
     * 		  on click distance.
     * restart: space bar
     * exit: esc button
     */
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Rectangle;
    import java.awt.event.KeyEvent;
    import java.text.DecimalFormat;
     
    public class FlyingHero extends Frame {
     
    	private static final long serialVersionUID = -2450477630768116721L;
    	protected static final int TEMPO = 80; // game speed (lower=faster, default
    											// 80)
    	private static int DEFAULT_FPS = 100;
    	private Ninja ninja; // the Ninja
    	private Plane plane;
    	private Planes planes;
    	private Bullet bullet;
    	private Bullets bullets;
    	private Zombies zombies;
    	private Zombie zombie;
    	private Background bg;
    	private boolean gameWin = false;
    	private ZombieTimer zt;
    	private PlaneTimer pt;
    	private int planesShot;
    	private int planesToWin = 10;
    	private static final int AREA_HEIGHT = 800; // height of play area
    	private int zombiesShot = 0;
    	private Font font;
    	private FontMetrics metrics;
    	private volatile boolean isOverQuitButton = false; // used by quit 'button'
    	private Rectangle quitArea;
    	private volatile boolean isOverPauseButton = false; // used by the pause
    														// 'button'
    	private Rectangle pauseArea;
    	private volatile boolean isOverRestartButton = false;// used by the restart
    															// 'button'
    	private Rectangle restartArea;
    	private DecimalFormat df = new DecimalFormat("0.##"); // 2 dp
    	private int i;
    	private int j;
    	private int bulletsLeft = 40;
     
    	// private int minesLeft = 5;
    	public FlyingHero(long period) {
    		super(period);
    	}
     
    	protected void mousePress(int x, int y) {
    		if (isOverPauseButton) {
    			if (super.isPaused) {
    				super.isPaused = false;
    			} else
    				super.isPaused = true;
    		} else if (isOverQuitButton)
    			super.running = false;
    		else if (isOverRestartButton) {
    			simpleRestart();
    		} else {
    			if(bulletsLeft>0 && !isPaused){
    			bullets.add(ninja.getX(), x, y);
    			bulletsLeft--;
    			}
    		}
    	} // end of mousePress
     
    	@Override
    	protected void mouseMove(int x, int y) {
    		if (running) { // stops problems with a rapid move after pressing 'quit'
    			isOverPauseButton = pauseArea.contains(x, y) ? true : false;
    			isOverQuitButton = quitArea.contains(x, y) ? true : false;
    			isOverRestartButton = restartArea.contains(x, y) ? true : false;
    		}
    	} // end of mouseMove
     
    	@Override
    	protected void keyPress(int keyCode) {
    		if (!isPaused && !gameOver) {
    			if (keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_A)
    				ninja.leftPressed(true);
    			else if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_D)
    				ninja.rightPressed(true);
    		}
    	} // end of keyPress
     
    	@Override
    	protected void keyRelease(int keyCode) {
    		if (!isPaused && !gameOver) {
    			if (keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_A)
    				ninja.leftPressed(false);
    			else if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_D)
    				ninja.rightPressed(false);
    		}
    	}
     
    	@Override
    	protected void simpleInitialize() {
    		// set up message font
    		font = new Font("SansSerif", Font.BOLD, 24);
    		metrics = this.getFontMetrics(font);
    		// specify screen areas for the buttons
    		pauseArea = new Rectangle(pWidth - 100, pHeight - 45, 70, 15);
    		quitArea = new Rectangle(pWidth - 100, pHeight - 20, 70, 15);
    		restartArea = new Rectangle(pWidth - 100, pHeight - 70, 70, 15);
    		// create game components
    		ninja = new Ninja(pWidth/2, pHeight / 2 + AREA_HEIGHT / 2, true);
    		bg = new Background(AREA_HEIGHT, pHeight, pWidth);
    		planes = new Planes(pWidth, pHeight, AREA_HEIGHT);
    		bullets = new Bullets(pWidth, pHeight, AREA_HEIGHT, ninja.getX());
    		zombies = new Zombies(pWidth, pHeight, AREA_HEIGHT);
    		zt = new ZombieTimer();
    		pt = new PlaneTimer();
    	} // end of simpleInitialize
     
    	@Override
    	protected void simpleUpdate() {
    		zt.zAdder(zombies);
    		for (i = 0; i < zombies.getZombies().size(); i++) { // loops through zombies, checks for hitting ninja, checks bullets against zombies
    			zombie = zombies.getZombies().get(i);
    			zombie.move();
    			if (ninja.hit(zombie)) {
    				gameOver = true;
    			}
    			for (j = 0; j < bullets.getBullets().size(); j++) {
    				bullet = bullets.getBullets().get(j);
    				bullet.move();
    				if (bullets.hitsZ(bullet, zombie)) {
    					zombiesShot++;
    					zombies.getZombies().remove(i); // zombie hit, remove it.
    				}// zombiesShot if
    			} // inner for
    		} // outer for
    		pt.pAdder(planes);
    		for (i = 0; i < planes.getPlanes().size(); i++) { // loops through planes, checks bullet hits
    			plane = planes.getPlanes().get(i);
    			plane.move();
    			for (j = 0; j < bullets.getBullets().size(); j++) {
    				bullet = bullets.getBullets().get(j);
    				bullet.move();
    				if (bullets.hitsP(bullet, plane)) {
    					planesShot++;
    					planes.getPlanes().remove(i); // plane hit, remove it.					
    				}// zombiesShot if
    			} // inner for
    		} // outer for
    		ninja.move();
    		if(planesShot == planesToWin){
    			gameWin = true;
    			gameOver = true;
    		}
    	} // end simpleUpdate
     
    	@Override
    	protected void simpleRender(Graphics gScr) {
    		// paint background
    		gScr.setColor(Color.gray);
    		gScr.fillRect(0, pHeight / 2 - AREA_HEIGHT / 2, pWidth, AREA_HEIGHT);
    		gScr.setColor(Color.white);
    		gScr.setFont(font);
    		// report frame count & average FPS and UPS at top left
    		gScr.drawString(
    				"Average FPS/UPS: " + df.format(averageFPS) + ", "
    						+ df.format(averageUPS), 20, 25); // was (10,55)
     
    		// report time used and zombiesShot at bottom left
    		String timeMsg = "Time Spent: " + currentGameTime + " secs";
    		gScr.drawString(timeMsg, 10, pHeight - 15);
    		String zombiesShotStr = "Zombies Killed: " + zombiesShot;
    		gScr.drawString(zombiesShotStr, 550, pHeight - 15);
    		String pShot = "Planes Shot Down: " + planesShot;
    		gScr.drawString(pShot, 900, pHeight - 15);
    		String ammoLeft = "Ammo Left: " + bulletsLeft;
    		gScr.drawString(ammoLeft, 10, pHeight - 40);
    		String instr = "Destroy " + planesToWin + " planes to survive the night! Watch out for zombies...";
    		gScr.drawString(instr, 500,  pHeight - 100);
    		gScr.setColor(Color.black);
    		// draw the pause, quit, and restart 'buttons'
    		drawButtons(gScr);
     
    		// draw area boundaries
    		int topHeight = pHeight / 2 - AREA_HEIGHT / 2;
    		int bottomHeight = pHeight / 2 + AREA_HEIGHT / 2;
    		gScr.setColor(Color.GREEN);
    		gScr.drawLine(0, bottomHeight, pWidth, bottomHeight);
    		gScr.setColor(Color.darkGray);
    		gScr.drawLine(0, topHeight, pWidth, topHeight);
     
    		// draw game elements
    		bg.draw(gScr); // background
    		for (i = 0; i < bullets.getBullets().size(); i++) { // bullets in action
    			bullet = bullets.getBullets().get(i);
    			bullet.draw(gScr);
    		}
    		for (i = 0; i < zombies.getZombies().size(); i++) { // zombies in action
    			zombie = zombies.getZombies().get(i);
    			zombie.draw(gScr);
    		}
    		for (i = 0; i < planes.getPlanes().size(); i++) { // planes in action
    			plane = planes.getPlanes().get(i);
    			plane.draw(gScr);
    		}
    		ninja.draw(gScr); // ninja
    	} // end of simpleRender
     
    	private void drawButtons(Graphics g) {
    		g.setColor(Color.white);
     
    		// draw the pause 'button'
    		if (isOverPauseButton)
    			g.setColor(Color.green);
     
    		g.drawOval(pauseArea.x, pauseArea.y, pauseArea.width, pauseArea.height);
    		if (isPaused)
    			g.drawString("Paused", pauseArea.x, pauseArea.y + 10);
     
    		else
    			g.drawString("Pause", pauseArea.x + 5, pauseArea.y + 10);
     
    		if (isOverPauseButton)
    			g.setColor(Color.white);
     
    		// draw the quit 'button'
    		if (isOverQuitButton)
    			g.setColor(Color.green);
     
    		g.drawOval(quitArea.x, quitArea.y, quitArea.width, quitArea.height);
    		g.drawString("Quit", quitArea.x + 15, quitArea.y + 10);
     
    		if (isOverQuitButton)
    			g.setColor(Color.white);
     
    		// draw the restart 'button'
    		if (isOverRestartButton)
    			g.setColor(Color.green);
     
    		g.drawOval(restartArea.x, restartArea.y, restartArea.width,
    				restartArea.height);
    		g.drawString("Restart", restartArea.x, restartArea.y + 10);
     
    		if (isOverRestartButton)
    			g.setColor(Color.white);
     
    	} // end of drawButtons
     
    	@Override
    	protected void gameOverMessage(Graphics g)
    	// center the game-over message in the panel
    	{
    		if(!gameWin){
    		ninja.drawLoss(g);
    		String msg = "You're Dead!";
    		String msg2 = "Zombies Killed: " + zombiesShot;
    		String msg3 = "Planes Destroyed: " + planesShot;
    		String msg4 = "Press Space to Restart";
    		int x = (pWidth - metrics.stringWidth(msg)) / 2;
    		int y = (pHeight - metrics.getHeight()) / 2;
    		int x2 = (pWidth - metrics.stringWidth(msg2)) / 2;
    		int y2 = y + 2 * metrics.getHeight() + 5;
    		int x3 = (pWidth - metrics.stringWidth(msg3)) / 2;
    		int y3 = y + 3 * metrics.getHeight() + 5 / 2;
    		int x4 = (pWidth - metrics.stringWidth(msg4)) / 2;
    		int y4 = y + 4 * metrics.getHeight() + 5;
     
    		g.setColor(Color.red);
    		g.setFont(font);
    		g.drawString(msg, x, y);
    		g.drawString(msg2, x2, y2);
    		g.drawString(msg3, x3, y3);
    		g.drawString(msg4, x4, y4);
    		}
    		else{
    			bg.drawWin(g);
    			ninja.drawWin(g);
    			String msg = "You Survived the Night!";
    			String msg2 = "Zombies Killed: " + zombiesShot;
    			String msg3 = "Planes Destroyed: " + planesShot;
    			String msg4 = "Press Space to Restart";
    			int x = (pWidth - metrics.stringWidth(msg)) / 2;
    			int y = (pHeight - metrics.getHeight()) / 2;
    			int x2 = (pWidth - metrics.stringWidth(msg2)) / 2;
    			int y2 = y + 2 * metrics.getHeight() + 5;
    			int x3 = (pWidth - metrics.stringWidth(msg3)) / 2;
    			int y3 = y + 3 * metrics.getHeight() + 5 / 2;
    			int x4 = (pWidth - metrics.stringWidth(msg4)) / 2;
    			int y4 = y + 4 * metrics.getHeight() + 5;
     
    			g.setColor(Color.red);
    			g.setFont(font);
    			g.drawString(msg, x, y);
    			g.drawString(msg2, x2, y2);
    			g.drawString(msg3, x3, y3);
    			g.drawString(msg4, x4, y4);
    		}
     
    	} // end of gameOverMessage
     
    	@Override
    	protected void simpleRestart() {
    		// reinitialize necessary game components
    		ninja = new Ninja(pWidth/2, pHeight / 2 + AREA_HEIGHT / 2, true);
    		bg = new Background(AREA_HEIGHT, pHeight, pWidth);
    		planes = new Planes(pWidth, pHeight, AREA_HEIGHT);
    		bullets = new Bullets(pWidth, pHeight, AREA_HEIGHT, ninja.getX());
    		zombies = new Zombies(pWidth, pHeight, AREA_HEIGHT);
    		zt = new ZombieTimer();
    		pt = new PlaneTimer();
    		gameWin = false;
    		zombiesShot = 0;
    		planesShot = 0;
    		bulletsLeft = 40;
    		currentStartTime = System.nanoTime();
    		currentGameTime = 0;
    		gameOver = false;
    	} // end simpleRestart
     
    	public static void main(String args[]) {
    		int fps = DEFAULT_FPS;
    		if (args.length != 0)
    			fps = Integer.parseInt(args[0]);
     
    		long period = (long) 1000.0 / fps;
    		System.out.println("fps: " + fps + "; period: " + period + " ms");
    		new FlyingHero(period * 1000000L); // ms --> nanosecs
    	} // end of main
     
    } // end of FlyingHero class


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Converting application to applet in eclipse

    An easy way is to rewrite the JFrame app to have a move all the the GUI stuff to a new JPanel that can either be added to the JFrame or to the JApplet.
    Those two classes would only be containers for all the GUI that was moved to the new JPanel and the only statements would be what was need to add the new JPanel to the container provided.
    The JFrame class would need to set the size, provide for closing and set itself visible.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Oct 2011
    Posts
    40
    My Mood
    Stressed
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Converting application to applet in eclipse

    Okay, I don't really understand what you mean. Should I change the frame class into a panel, then add it to a new class called applet?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Converting application to applet in eclipse

    I was suggesting that all the GUI code go into a new class that the JFrame and JApplet code would add to themselves:
    public class OneClass extends JFrame{
      OneClass() {
          add(new TheNewClassWithAllTheGUI());
          // Do the JFrame stuff
          setSize(...
          setLocation(...
          setDefaultCloseOperation(...
          setVisible(true);
      } // end constructor
    } //  end class
    public class AnotherClass extends JApplet {
        public void init() {
            add(new TheNewClassWithAllTheGUI());
            ...
        }
        ....
    } // end Class

    Move all the GUI logic to TheNewClassWithAllTheGUI
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 24
    Last Post: August 4th, 2014, 12:49 PM
  2. Replies: 1
    Last Post: October 20th, 2012, 12:21 PM
  3. Beginners Eclipse Tutorial. How to run first java application on Eclipse?
    By JavaPF in forum Java Code Snippets and Tutorials
    Replies: 13
    Last Post: June 24th, 2011, 12:26 AM
  4. Replies: 0
    Last Post: December 3rd, 2009, 04:43 PM

Tags for this Thread