从JFrame更改为JApplet

时间:2015-06-10 17:20:05

标签: java swing deployment jframe japplet

我试图将我使用JFrame创建的一些Java应用程序更改为JApplets,这样它们就可以放在我也想做的网站上。我只是想知道在我的程序中需要改变什么才能实现这一目标。以下是其中一个程序的示例(我试图通过更改扩展和一些属性来运行此程序,但它只是在进程仍在运行时消失):

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 个答案:

答案 0 :(得分:0)

使用此代码,您有两个版本(JFrame和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);
    }
...