Changing from JFrame to JApplet

773 views Asked by At

I'm trying to change some Java applications that I made using JFrame to JApplets so they can be placed on a website that I am also trying to make. I am just wondering what needs to be changed in my programs to accomplish this. Here is an example of one of the programs (I tried to run this one with just changing the extension and some attributes, but it just disappears with the process still running):

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener; 
import javax.swing.*;

@SuppressWarnings("serial")
public class Snake extends JApplet//extends JFrame
{
    private Panel panel;
    Dimension x = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    private final int SCALER = 25, LENGTH = (int) x.getWidth()/SCALER-1, 
                      HEIGHT = (int) x.getHeight()/SCALER-1;

public static void main(String[] args)
{
    new Snake();
}

public Snake()
{
    //setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(x);
    //setTitle("SNAKE");
    //setResizable(false);
    panel = new Panel(20,20,SCALER);
    add(panel, BorderLayout.CENTER);
    Handler handler = new Handler();
    addKeyListener(handler);
    setVisible(true);
}

private class Handler implements KeyListener
{
    public void keyPressed(KeyEvent e)
    {
        switch (e.getKeyCode())
        {
            case KeyEvent.VK_LEFT:
            panel.pass(270);
            break;
            case KeyEvent.VK_RIGHT:
            panel.pass(90);
            break;
            case KeyEvent.VK_UP:
            panel.pass(0);
            break;
            case KeyEvent.VK_DOWN:
            panel.pass(180);        
            break;
        }
    }

    public void keyReleased(KeyEvent e) 
    {

    }

    public void keyTyped(KeyEvent e) 
    {

    }
  }
}
1

There are 1 answers

0
SandroMarques On

With this code, you have both versions (JFrame and JApplet)

public class Snake extends JApplet 
{
    public static void main(String[] args)
    {
        // JFrame
        JFrame frame = new JFrame();
        frame.setTitle("Snake");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Applet
        JApplet applet = new Snake();
        applet.init();

        // Insert the Applet into JFrame
        frame.getContentPane().add(applet);
        frame.pack();
        frame.setVisible(true);
    }
...