Converting from Applet to JFrame

Hey guys, I am coming along pretty good in getting a lot of stuff done on my game, today I’m wanting to have it so that I can have a normal window for my game instead of having it run in an applet. I’m still somewhat new to java so I’m kind of lost on how to get it working with my code. Heres what I have right now, 2 classes one for my GameLoop and one for my Display stuff, I really have no clue where and how to start getting JFrame to work with this, but if any of you are able to help out that would be awsome!


import java.awt.Graphics;
import java.awt.Image;

public class Display extends GameLoop implements State  { // extends gameloop class to Display.
  public Image backbuffer;
  public static Graphics bb;

  public void init(){                 //this method opens the Applet window 
    setSize (257,225);
    Thread th= new Thread (this);
    th.start();
    backbuffer=createImage(256,224); //backbuffer image size
    bb= backbuffer.getGraphics();
  }
 
//TODO: fix flickering, may be in here...
  public void paint (Graphics g) { //this method paints.
    //draws foreground and menus
	  stateStack.render();
    //copy back buffer to front buffer
    g.drawImage(backbuffer, 0, 0, this);  
  }   
}


import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;

public class GameLoop extends Applet implements Runnable, KeyListener, State {
 public StateStack stateStack = new StateStack();
 
  
  final double gameplayFrequency=1000/60;
  public static  boolean [] keysPressed = new boolean[256];
  public static boolean [] keysDown = new boolean[256];
  public static boolean [] keysUp = new boolean[256];
  private static boolean [] keysPrevious = new boolean[256];
  public boolean running=true;
   //run method
  public void run() {
	 //initializers
	InventoryState.initialize();
    GamePlayState.initialize();
    GamePlayState.entityAdder();
    //------------------------
    addKeyListener(this); 
    double lastGameplayTime= System.currentTimeMillis();
    double now;
    double counting = 0;
    while(running)
    { 
      //this enables frame skipping
      now = System.currentTimeMillis();
      if(now>lastGameplayTime){
        counting=0;
        while (now>lastGameplayTime)
        {
          counting++;
          if(counting>=10){
            lastGameplayTime=System.currentTimeMillis();
            break;
          }
          lastGameplayTime+=gameplayFrequency; 
          stateStack.update();
          
          keyUpdate();
        }
        repaint();                         //this refreshes the screen
        
      }
    }
    now=System.currentTimeMillis();
    if(now>lastGameplayTime){
      try {Thread.sleep((long) (now-lastGameplayTime));}
      catch (InterruptedException e) {e.printStackTrace();} 
    }
  }

set your Display class to extend JPanel then in your class with the main method put:


class Main extends JFrame{//whatever class holds you main method
public static JFrame frame;//public and static so other classes can access it. Might want to use a getter and setter here
public Main(){
     frame=new JFrame("frame");// Create new JFrame
     frame.add(new Display());//add the Display (this is posible because the Display class extends JPanel)
     frame.setSize(width,height);//Set the size of the window
     frame.setDefaultCloseOpperation(EXIT_ON_CLOSE);//Make sure all processes are closed when the window is closed
     frame.setLocationRelativeTo(null);//Centers window
     frame.setVisible(true);//Make the window visible
}

public static void main(String[] args){
     new Main();//instantiate the Main class, this has to happen
}

}

in your Display class, your paint method should look like this:


public void paint(Graphics g){//when repaint is called, this method will run
        super.paint(g);
	Graphics2D g2d = (Graphics2D) g;//Graphics2D is a better Graphics, I would recommend using it
        stateStack.render();
        g2d.drawImage(backbuffer, 0, 0, this);  
}


Hope this helps and good luck! :wink:

Thank you so much!! I am getting a “ClassCastException” though, heres how I have my code:


import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.JPanel;
import javax.swing.JFrame;

public class Display extends JPanel implements State  { // oldcode extends gameloop class to Display.
  public Image backbuffer;
  public static Graphics bb;
  
  public void paint(Graphics g){
	  super.paint(g);
	  Graphics2D g2d= (Graphics2D) g;
	  GameLoop.stateStack.render();
	  g2d.drawImage(backbuffer, 0, 0, this);
  }


import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class GameLoop extends JFrame implements Runnable, KeyListener, State {

 
  public static StateStack stateStack = new StateStack(); //in old code this was not static
  final double gameplayFrequency=1000/60;
  public static  boolean [] keysPressed = new boolean[256];
  public static boolean [] keysDown = new boolean[256];
  public static boolean [] keysUp = new boolean[256];
  private static boolean [] keysPrevious = new boolean[256];
  public boolean running=true;
  public static JFrame frame; 
  
  public GameLoop(){
	     frame=new JFrame("frame");// Create new JFrame
	     frame.add(new Display());//add the Display (this is posible because the Display class extends JPanel)
	     frame.setSize(200,200);//Set the size of the window
	     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Make sure all processes are closed when the window is closed
	     frame.setLocationRelativeTo(null);//Centers window
	     frame.setVisible(true);//Make the window visible
	}
  
   //run method
  public void run() {
	 //initializers
	new GameLoop();
	InventoryState.initialize();
    GamePlayState.initialize();
    GamePlayState.entityAdder();
    //------------------------
    addKeyListener(this); 
    double lastGameplayTime= System.currentTimeMillis();
    double now;
    double counting = 0;
    while(running)
    { 
      //this enables frame skipping
      now = System.currentTimeMillis();
      if(now>lastGameplayTime){
        counting=0;
        while (now>lastGameplayTime)
        {
          counting++;
          if(counting>=10){
            lastGameplayTime=System.currentTimeMillis();
            break;
          }
          lastGameplayTime+=gameplayFrequency; 
          stateStack.update();
          
          keyUpdate();
        }
        repaint();                         //this refreshes the screen
        
      }
    }
    now=System.currentTimeMillis();
    if(now>lastGameplayTime){
      try {Thread.sleep((long) (now-lastGameplayTime));}
      catch (InterruptedException e) {e.printStackTrace();} 
    }
  }

I believe that the problem is on line 27 of my GameLoop Class. Also I actually do not have a main method in this program and so I instantiate on line 37, I dont think that would cause the problem though.

[quote]Also I actually do not have a main method in this program and so I instantiate on line 37, I dont think that would cause the problem though.
[/quote]
Wait, do I understand you wrong? How do you run your program?
And how (where) are you getting your error? What is it exactly?

Nothing should throw that exception ??? . Post exactly what is outputted from the console

Wait, do I understand you wrong? How do you run your program?
And how (where) are you getting your error? What is it exactly?
[/quote]
it would just go through the run() method

java.lang.ClassCastException: Display cannot be cast to java.applet.Applet
at sun.applet.AppletPanel.createApplet(Unknown Source)
at sun.applet.AppletPanel.runLoader(Unknown Source)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

Is it actually cause I need to have a thread running on this? because before my display class extended my GameLoop class and the thread was in my display class

The run() method only goes for Applets doesnt it?
You kept using the word “Applet” or something applet related at some position, thats why.
Maybe you try to run the class as an applet but it is none.

Use “public static void main(String[] args)”.

ohhh that makes since, so I use
public static void main(String[] args)
instead of public void run() like I have on line 35?

and then I take out “Runnable” from line 13?

This and I think you need a main method. just make a main Method in GameLoop that looks like:


public static void main(String args[]){
new Thread(this).start();
}

He gets the run method from implementing Runnable. The Runnable interface doesn’t just work with applets.

You were faster.
Just place the posted run method somewhere and leave everything else as it is.

cannot use this in static context

new Thread(new GameLoop()).start();

Remove “new GameLoop();” from “run()”.

I’m still getting the same exception
java.lang.ClassCastException: Display cannot be cast to java.applet.Applet
at sun.applet.AppletPanel.createApplet(Unknown Source)
at sun.applet.AppletPanel.runLoader(Unknown Source)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)


import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class GameLoop extends JFrame implements Runnable, KeyListener, State {

 
  public static StateStack stateStack = new StateStack(); //in old code this was not static
  final double gameplayFrequency=1000/60;
  public static  boolean [] keysPressed = new boolean[256];
  public static boolean [] keysDown = new boolean[256];
  public static boolean [] keysUp = new boolean[256];
  private static boolean [] keysPrevious = new boolean[256];
  public boolean running=true;
  public static JFrame frame; 
  
  public GameLoop(){
	     frame=new JFrame("frame");// Create new JFrame
	     frame.add(new Display());//add the Display (this is posible because the Display class extends JPanel)
	     frame.setSize(200,200);//Set the size of the window
	     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Make sure all processes are closed when the window is closed
	     frame.setLocationRelativeTo(null);//Centers window
	     frame.setVisible(true);//Make the window visible
	}
  
  public static void main(String args[]){
   new Thread(new GameLoop()).start();
}
  
   //run method
  public void run() {
	 //initializers
	new GameLoop();
	InventoryState.initialize();
    GamePlayState.initialize();
    GamePlayState.entityAdder();
    //------------------------
    addKeyListener(this); 
    double lastGameplayTime= System.currentTimeMillis();
    double now;
    double counting = 0;
    while(running)
    { 
      //this enables frame skipping
      now = System.currentTimeMillis();
      if(now>lastGameplayTime){
        counting=0;
        while (now>lastGameplayTime)
        {
          counting++;
          if(counting>=10){
            lastGameplayTime=System.currentTimeMillis();
            break;
          }
          lastGameplayTime+=gameplayFrequency; 
          stateStack.update();
          
          keyUpdate();
        }
        repaint();                         //this refreshes the screen
        
      }
    }
    now=System.currentTimeMillis();
    if(now>lastGameplayTime){
      try {Thread.sleep((long) (now-lastGameplayTime));}
      catch (InterruptedException e) {e.printStackTrace();} 
    }
  }

sorry if im being a bother about this x.x lol

I removed “new GameLoop();” as well and still the same exception

Please, its getting messy, post everything.

Ok so heres everything.


import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class GameLoop extends JFrame implements Runnable, KeyListener, State {

 
  public static StateStack stateStack = new StateStack(); //in old code this was not static
  final double gameplayFrequency=1000/60;
  public static  boolean [] keysPressed = new boolean[256];
  public static boolean [] keysDown = new boolean[256];
  public static boolean [] keysUp = new boolean[256];
  private static boolean [] keysPrevious = new boolean[256];
  public boolean running=true;
  public static JFrame frame; 
  
  public GameLoop(){
	     frame=new JFrame("frame");// Create new JFrame
	     frame.add(new Display());//add the Display (this is posible because the Display class extends JPanel)
	     frame.setSize(200,200);//Set the size of the window
	     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Make sure all processes are closed when the window is closed
	     frame.setLocationRelativeTo(null);//Centers window
	     frame.setVisible(true);//Make the window visible
	}
  
  public static void main(String args[]){
   new Thread(new GameLoop()).start();
}
  
   //run method
  public void run() {
	 //initializers
	InventoryState.initialize();
    GamePlayState.initialize();
    GamePlayState.entityAdder();
    //------------------------
    addKeyListener(this); 
    double lastGameplayTime= System.currentTimeMillis();
    double now;
    double counting = 0;
    while(running)
    { 
      //this enables frame skipping
      now = System.currentTimeMillis();
      if(now>lastGameplayTime){
        counting=0;
        while (now>lastGameplayTime)
        {
          counting++;
          if(counting>=10){
            lastGameplayTime=System.currentTimeMillis();
            break;
          }
          lastGameplayTime+=gameplayFrequency; 
          stateStack.update();
          
          keyUpdate();
        }
        repaint();                         //this refreshes the screen
        
      }
    }
    now=System.currentTimeMillis();
    if(now>lastGameplayTime){
      try {Thread.sleep((long) (now-lastGameplayTime));}
      catch (InterruptedException e) {e.printStackTrace();} 
    }
  }
          //key press methods
	
		public void keyPressed(KeyEvent e) { //this method controls what to do when a key is pressed
			keysPressed[e.getKeyCode()] = true;
			keysDown[e.getKeyCode()]=true;
		}

		public void keyReleased(KeyEvent e) { //this method controls what happens when a key is released from being pressed
			keysPressed[e.getKeyCode()] = false;
			keysUp[e.getKeyCode()]=true;
		}
		
		public void keyTyped(KeyEvent arg0) {	//ignore this method
		}
		
		//this method updates keysDown and keysUp so that they return to 'false' each frame.
		private void keyUpdate(){
			for(int i=255; i>0;i--)
			keysDown[i] = false;
			for(int i=255; i>0;i--)
			keysUp[i]= false;
			for(int i=256; i>keysPrevious.length; i--)
			keysPrevious[i]=false;
		}
		
		
		//ignore these methods
		public void update() {	
		}
	
		
		public void render() {		
		}
	}




import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.JPanel;
import javax.swing.JFrame;

public class Display extends JPanel implements State  { // oldcode extends gameloop class to Display.
  public Image backbuffer;
  public static Graphics bb;
  
  public void paint(Graphics g){
	  super.paint(g);
	  Graphics2D g2d= (Graphics2D) g;
	  GameLoop.stateStack.render();
	  g2d.drawImage(backbuffer, 0, 0, this);
  }

  
  
public void update() {
}

public void render() {
}
  
  
  // all of this is old code
 /* public void init(){                 //this method opens the Applet window 
    setSize (257,225);
    Thread th= new Thread (this);
    th.start();
    backbuffer=createImage(256,224); //backbuffer image size
    bb= backbuffer.getGraphics();
  }
 
//TODO: fix flickering, may be in here...
  public void paint (Graphics g) { //this method paints.
    //draws foreground and menus
	  stateStack.render();
    //copy back buffer to front buffer
    g.drawImage(backbuffer, 0, 0, this);  
  }   */
}


Wait a minute… are you running this program as an applet in eclipse? Because when you change from an applet, you have to tell eclipse to run from the main method. (I think)

Press the dropdown arrow by the run button in eclipse and select “run as> Java Application” while in the GameLoop Class

Sweet now I at least get my window instead of an applet, I just got an assload of other exception to take care of in my states and everything