编程语言
首页 > 编程语言> > Java JApplet到JFrame

Java JApplet到JFrame

作者:互联网

我想将JApplet转换为JFrame.我在互联网上找到了一个单词搜索游戏的代码.我想在一个类的演示中使用此代码.但我不想在applet中使用它.我要在此处粘贴的代码大约有7,000个字符.我尝试使用JApplet并扩展JFrame,然后将用于初始化的所有代码放入构造函数(零自变量构造函数)中.这导致大约十个我无法修复的错误.我想做一个单词搜索游戏,我找到了一个很好的例子,但是我无法在Eclipse中运行它.

class WordSearch extends JApplet
implements Runnable, KeyListener, MouseListener, MouseMotionListener {

    // Copyright information.

    String copyName = "Word Search";
    String copyVers = "Version 1.1";
    String copyInfo = "Copyright 1999-2001 by Mike Hall";
    String copyLink = "http://www.brainjar.com";
    String copyText = copyName + '\n' + copyVers + '\n'
            + copyInfo + '\n' + copyLink;

    // Thread control variables.

    Thread loopThread;    // Main thread.

    // Constants

    static final int DELAY = 50;    // Milliseconds between screen updates.

    static final int INIT  =  1;    // Game states.
    static final int PLAY  =  2;
    static final int OVER  =  3;

    // Parameters and defaults.

    Color  scrnFgColor = Color.black;             // Background color.
    Color  scrnBgColor = Color.white;             // Foreground color.
    Color  scrnBdColor = Color.black;             // Border color.   
    String scrnFontStr = "Helvetica,bold,12";     // Font.

    Color  bttnFgColor = Color.black;             // Button background color.
    Color  bttnBgColor = Color.lightGray;         // Button foreground color.
    String bttnFontStr = "Dialog,bold,10";        // Button font.

    Color  gridFgColor = Color.black;             // Grid text color.
    Color  gridBgColor = Color.white;             // Grid background color.
    Color  gridHiColor = Color.yellow;            // Grid highlight color.
    Color  gridFdColor = Color.lightGray;         // Grid found color.
    String gridFontStr = "Courier,plain,14";      // Grid font.

    Color  listFgColor = Color.black;             // List text color.
    Color  listBgColor = Color.white;             // List background color.
    Color  listFdColor = Color.lightGray;         // List found color.
    String listFontStr = "Helvetica,plain,12";    // List font.

    int    gridRows    = 15;                      // Grid rows.
    int    gridCols    = 15;                      // Grid columns.
    int    gridSize    = 20;                      // Grid cell size.

    Vector files       = new Vector();            // List if text file URLs.

    // Global variables.

    static Vector words;    // Word list.

    Font scrnFont;    // Screen font.
    Font bttnFont;    // Screen font.
    Font gridFont;    // Grid font.
    Font listFont;    // List font.

    // Display elements.

    WSGrid   grid;
    WSList   list;
    WSButton newGame;
    WSButton solveGame;
    WSButton scrollUp;
    WSButton scrollDn;

    // File data.

    int fileNum;

    // Game data.

    int gap = 4;     // Gap between display elements.

    int    gameState;    // Game state.
    int    scroll;       // Scroll direction.
    int    count;        // Number of words found.
    long   startTime;    // Start time of current game.
    String timeText;     // Elapsed time text.
    String statText;     // Words found/total text.
    String subjText;     // Word list subject, from file.

    // Off screen image.

    Dimension offDimension;
    Image     offImage;
    Graphics  offGraphics;

    // Applet information.

    public String getAppletInfo() {

        return(copyText);
    }

    public void init() {

        Dimension d = getSize();
        Font f;
        FontMetrics fm;
        String s;
        StringTokenizer st;
        int n;
        Polygon p;
        int x, y;
        int w, h;

        // Display copyright information.

        System.out.println(copyText);

        // Set up mouse and key event handling and set focus to the applet window.

        addKeyListener(this);
        addMouseListener(this);
        addMouseMotionListener(this);
        requestFocus();

        // Get colors.

        s = getParameter("screencolors");
        if (s != null) {
            st = new StringTokenizer(s, ",");
            scrnFgColor = getColorParm(st.nextToken());
            scrnBgColor = getColorParm(st.nextToken());
            scrnBdColor = getColorParm(st.nextToken());
        }
        s = getParameter("buttoncolors");
        if (s != null) {
            st = new StringTokenizer(s, ",");
            bttnFgColor = getColorParm(st.nextToken());
            bttnBgColor = getColorParm(st.nextToken());
        }
        s = getParameter("gridcolors");
        if (s != null) {
            st = new StringTokenizer(s, ",");
            gridFgColor = getColorParm(st.nextToken());
            gridBgColor = getColorParm(st.nextToken());
            gridFdColor = getColorParm(st.nextToken());
            gridHiColor = getColorParm(st.nextToken());
        }
        s = getParameter("listcolors");
        if (s != null) {
            st = new StringTokenizer(s, ",");
            listFgColor = getColorParm(st.nextToken());
            listBgColor = getColorParm(st.nextToken());
            listFdColor = getColorParm(st.nextToken());
        }

        // Get fonts.

        scrnFont = getFontParm(scrnFontStr);
        s = getParameter("screenfont");
        if (s != null)
            if ((f = getFontParm(s)) != null)
                scrnFont = f;
        bttnFont = getFontParm(bttnFontStr);
        s = getParameter("buttonfont");
        if (s != null)
            if ((f = getFontParm(s)) != null)
                bttnFont = f;
        gridFont = getFontParm(gridFontStr);
        s = getParameter("gridfont");
        if (s != null)
            if ((f = getFontParm(s)) != null)
                gridFont = f;
        listFont = getFontParm(listFontStr);
        s = getParameter("listfont");
        if (s != null)
            if ((f = getFontParm(s)) != null)
                listFont = f;

        // Get grid size.

        s = getParameter("gridsize");
        if (s != null) {
            st = new StringTokenizer(s, ",");
            if ((n = Integer.parseInt(st.nextToken())) > 0)
                gridRows = n;
            if ((n = Integer.parseInt(st.nextToken())) > 0)
                gridCols = n;
            if ((n = Integer.parseInt(st.nextToken())) > 0)
                gridSize = n;
        }

        // Get list of word file URLs.

        s = getParameter("files");
        if (s != null) {
            st = new StringTokenizer(s, ",");
            while (st.hasMoreTokens())
                files.addElement(st.nextToken());
        }

        // Create and position letter grid.

        grid = new WSGrid(gridRows, gridCols, gridSize, gridFont);
        grid.setColors(gridFgColor, gridBgColor, scrnBdColor, gridFdColor,
                gridHiColor);
        grid.clear();

        // Create and position word list.

        fm = getFontMetrics(listFont);
        x = grid.x + grid.width + gap;
        w = d.width - x;
        h = grid.height - 2 * (fm.getHeight() + gap);
        list = new WSList(w, h, listFont);
        list.x = x;
        list.y = grid.y + fm.getHeight() + gap;
        list.setColors(listFgColor, listBgColor, scrnBdColor, listFdColor);

        // Create and position scroll buttons above and below work list.

        fm = getFontMetrics(bttnFont);
        w = list.width;
        h = fm.getHeight();
        p = new Polygon();
        p.addPoint(0, -h / 2 + 2);
        p.addPoint(-fm.getMaxAdvance() / 2, h / 2 - 2);
        p.addPoint(fm.getMaxAdvance() / 2, h / 2 - 2);
        scrollUp = new WSButton(p, w, h);
        scrollUp.x = list.x;
        scrollUp.y = grid.y;
        scrollUp.setColors(bttnFgColor, bttnBgColor, scrnBdColor);
        p = new Polygon();
        p.addPoint(0, h / 2 - 2);
        p.addPoint(-fm.getMaxAdvance() / 2, -h / 2 + 2);
        p.addPoint(fm.getMaxAdvance() / 2, -h / 2 + 2);
        scrollDn = new WSButton(p, w, h);
        scrollDn.x = list.x;
        scrollDn.y = list.y + list.height + gap;
        scrollDn.setColors(bttnFgColor, bttnBgColor, scrnBdColor);

        // Create and position text buttons under letter grid.

        fm = getFontMetrics(bttnFont);

        s = "New Game";
        w = fm.stringWidth(s) + fm.getMaxAdvance();
        h = 3 * fm.getHeight() / 2;
        newGame = new WSButton(s, bttnFont, w, h);
        newGame.setColors(bttnFgColor, bttnBgColor, scrnBdColor);

        s = "Solve Game";
        w = fm.stringWidth(s) + fm.getMaxAdvance();
        solveGame = new WSButton(s, bttnFont, w, h);
        solveGame.setColors(bttnFgColor, bttnBgColor, scrnBdColor);

        fm = getFontMetrics(scrnFont);
        x = (grid.width - (newGame.width + solveGame.width + gap)) / 2;
        y = grid.x + grid.height + fm.getHeight() + fm.getMaxDescent() + 2 * gap;
        newGame.x = x;
        newGame.y = y;
        solveGame.x = x + newGame.width + gap;
        solveGame.y = y;

        // Initialize game data.

        fileNum = 0;
        scroll = 0;
        timeText = "";
        statText = "";
        subjText = "";
        words = new Vector();
        grid.fill();
        endGame();
        gameState = INIT;
    }

    public Color getColorParm(String s) {

        int r, g, b;

        // Check if a pre-defined color is specified.

        if (s.equalsIgnoreCase("black"))
            return(Color.black);
        if (s.equalsIgnoreCase("blue"))
            return(Color.blue);
        if (s.equalsIgnoreCase("cyan"))
            return(Color.cyan);
        if (s.equalsIgnoreCase("darkGray"))
            return(Color.darkGray);
        if (s.equalsIgnoreCase("gray"))
            return(Color.gray);
        if (s.equalsIgnoreCase("green"))
            return(Color.green);
        if (s.equalsIgnoreCase("lightGray"))
            return(Color.lightGray);
        if (s.equalsIgnoreCase("magenta"))
            return(Color.magenta);
        if (s.equalsIgnoreCase("orange"))
            return(Color.orange);
        if (s.equalsIgnoreCase("pink"))
            return(Color.pink);
        if (s.equalsIgnoreCase("red"))
            return(Color.red);
        if (s.equalsIgnoreCase("white"))
            return(Color.white);
        if (s.equalsIgnoreCase("yellow"))
            return(Color.yellow);

        // If the color is specified in HTML format, build it from the red, green
        // and blue values.

        if (s.length() == 7 && s.charAt(0) == '#') {
            r = Integer.parseInt(s.substring(1,3),16);
            g = Integer.parseInt(s.substring(3,5),16);
            b = Integer.parseInt(s.substring(5,7),16);
            return(new Color(r, g, b));
        }

        // If we can't figure it out, default to black.

        return(Color.black);
    }

    public Font getFontParm(String s) {

        String t, fontName;
        StringTokenizer st;
        int n, fontStyle, fontSize;

        fontName = "";
        fontStyle = -1;
        fontSize = -1;

        // Parse font name.

        st = new StringTokenizer(s, ",");
        t = st.nextToken();
        if (t.equalsIgnoreCase("Courier"))
            fontName = "Courier";
        else if (t.equalsIgnoreCase("Dialog"))
            fontName = "Dialog";
        else if (t.equalsIgnoreCase("Helvetica"))
            fontName = "Helvetica";
        else if (t.equalsIgnoreCase("Symbol"))
            fontName = "Symbol";
        else if (t.equalsIgnoreCase("TimesRoman"))
            fontName = "TimesRoman";

        // Parse font style.

        t = st.nextToken();
        if (t.equalsIgnoreCase("plain"))
            fontStyle = Font.PLAIN;
        else if (t.equalsIgnoreCase("bold"))
            fontStyle = Font.BOLD;
        else if (t.equalsIgnoreCase("italic"))
            fontStyle = Font.ITALIC;
        else if (t.equalsIgnoreCase("boldItalic"))
            fontStyle = Font.BOLD + Font.ITALIC;

        // Parse font size.

        t = st.nextToken();
        if ((n = Integer.parseInt(t)) > 0)
            fontSize = n;

        // Return the specified font.

        if (fontName != "" && fontStyle >= 0 && fontSize >= 0)
            return(new Font(fontName, fontStyle, fontSize));

        // If we can't figure it out, return a null value.

        return (Font) null;
    }

    public void start() {

        if (loopThread == null) {
            loopThread = new Thread(this);
            loopThread.start();
        }
    }

    public void stop() {

        if (loopThread != null) {
            loopThread.stop();
            loopThread = null;
        }
    }

    public void run() {

        long threadTime, elapsedTime;
        Date date;
        int m, s;
        String mm, ss;

        // Lower this thread's priority and get the current time.

        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        threadTime = System.currentTimeMillis();

        // This is the main loop.

        while (Thread.currentThread() == loopThread) {

            // Scroll word list.

            list.scroll += scroll;

            // Update game time.

            if (gameState == PLAY) {
                elapsedTime = threadTime - startTime;
                m = (int) (elapsedTime / 60000);
                s = (int) ((elapsedTime - 60000 * m) / 1000);
                mm = Integer.toString(m);
                ss = Integer.toString(s);
                if (mm.length() < 2)
                    mm = "0" + mm;
                if (ss.length() < 2)
                    ss = "0" + ss;
                timeText = "Time: " + mm + ":" + ss;
                statText = "Found: " + count + "/" + words.size();
            }

            // Update the screen and set the timer for the next loop.

            repaint();
            try {
                threadTime += DELAY;
                Thread.sleep(Math.max(0, threadTime - System.currentTimeMillis()));
            }
            catch (InterruptedException e) {
                break;
            }
        }
    }

    public void keyPressed(KeyEvent e) {

        // 'HOME' key: jump to web site (undocumented).

        if (e.getKeyCode() == KeyEvent.VK_HOME)
            try {
                getAppletContext().showDocument(new URL(copyLink));
            }
        catch (Exception excp) {}
    }

    public void keyReleased(KeyEvent e) {}

    public void keyTyped(KeyEvent e) {}

    public void mousePressed(MouseEvent e) {

        int x, y;

        x = e.getX();
        y = e.getY();

        // Check buttons.

        if (newGame.inside(x, y))
            initGame();
        if (gameState == PLAY && solveGame.inside(x, y))
            solveGame();
        if (gameState != INIT && scrollUp.inside(x, y))
            scroll = -1;
        if (gameState != INIT && scrollDn.inside(x, y))
            scroll = 1;

        // Check grid.

        if (gameState == PLAY && grid.inside(x, y)) {
            grid.select = true;
            grid.startX = x;
            grid.startY = y;
            grid.endX = x;
            grid.endY = y;
        }
    }

    public void mouseReleased(MouseEvent e) {

        // Stop any scrolling.

        scroll = 0;

        // If a selection was being made, check it.

        if (gameState == PLAY && grid.select) {
            grid.select = false;
            if (grid.checkSelection())
                if (++count >= words.size()) {
                    timeText += " Done!";
                    statText = "Found: " + count + "/" + words.size();
                    endGame();
                }
        }
    }

    public void mouseClicked(MouseEvent e) {}

    public void mouseEntered(MouseEvent e) {}

    public void mouseExited(MouseEvent e) {}

    public void mouseDragged(MouseEvent e) {

        if (gameState == PLAY && grid.select) {
            grid.endX = e.getX();
            grid.endY = e.getY();
        }
    }

    public void mouseMoved(MouseEvent e) {}

    public void initGame() {

        setWords();
        grid.select = false;
        grid.fill();
        list.scroll = 0;
        count = 0;
        startTime = System.currentTimeMillis();
        timeText = "";
        statText = "";
        gameState = PLAY;
    }

    public void solveGame() {

        WSWord ws;
        int i;

        // Mark all words as found.

        for (i = 0; i < words.size(); i++) {
            ws = (WSWord) words.elementAt(i);
            ws.found = true;
        }
        count = words.size();
        timeText = "Cheated!";
        endGame();
    }

    public void endGame() {

        gameState = OVER;
    }

    public void setWords() {

        String s;
        URL url;
        InputStream in;
        BufferedReader buf;

        // Clear word list.

        words.removeAllElements();

        // Get next file URL.

        if (fileNum >= files.size())
            fileNum = 0;
        s = (String) files.elementAt(fileNum);
        url = (URL) null;
        try {
            url = new URL(getDocumentBase(), s);
        }
        catch (Exception e) {}
        fileNum++;

        // Open it up and read list of words.

        subjText = "";
        try {
            in = url.openStream();
            buf = new BufferedReader(new InputStreamReader(in));
            while((s = buf.readLine()) != null)
                if (s.startsWith("#"))
                    subjText = "'" + s.substring(1) + "'";
                else if (s.length() > 0)
                    words.addElement(new WSWord(s));
        }
        catch (IOException e) {}
    }

    public void update(Graphics g) {

        paint(g);
    }

    public void paint(Graphics g) {

        Dimension d = getSize();
        FontMetrics fm;
        String s;
        int x, y;
        int w, h;

        // Create the off screen graphics context, if no good one exists.

        if (offGraphics == null || d.width != offDimension.width || d.height != offDimension.height) {
            offDimension = new Dimension(d.width, d.height);
            offImage = createImage(d.width, d.height);
            offGraphics = offImage.getGraphics();
        }

        // Color the applet background.

        offGraphics.setColor(scrnBgColor);
        offGraphics.fillRect(0, 0, d.width, d.height);

        // Draw each game element.

        grid.draw(offGraphics);
        list.draw(offGraphics);
        scrollUp.draw(offGraphics);
        scrollDn.draw(offGraphics);
        newGame.draw(offGraphics);
        solveGame.draw(offGraphics);

        // Display title, messages, etc. as appropriate.

        offGraphics.setColor(scrnFgColor);
        offGraphics.setFont(scrnFont);
        fm = offGraphics.getFontMetrics();

        if (gameState == INIT) {
            x = (grid.x + grid.width) / 2;
            y = (grid.y + grid.height) / 2;
            w = Math.max(fm.stringWidth(copyName), fm.stringWidth(copyVers));
            w = Math.max(w, fm.stringWidth(copyInfo));
            w = Math.max(w, fm.stringWidth(copyLink));
            w += fm.getMaxAdvance();
            h = 6 * fm.getHeight();
            offGraphics.setColor(gridFgColor);
            offGraphics.fillRect(x - w / 2, y - h / 2, w, h);
            offGraphics.setColor(gridBgColor);
            offGraphics.drawRect(x - w / 2 + 1, y - h / 2 + 1, w - 3, h - 3);

            offGraphics.drawString(copyName, x - fm.stringWidth(copyName) / 2, y - 2 * fm.getHeight());
            offGraphics.drawString(copyVers, x - fm.stringWidth(copyVers) / 2, y -     fm.getHeight());
            offGraphics.drawString(copyInfo, x - fm.stringWidth(copyInfo) / 2, y +     fm.getHeight());
            offGraphics.drawString(copyLink, x - fm.stringWidth(copyLink) / 2, y + 2 * fm.getHeight());
        }

        x = (grid.x + grid.width - fm.stringWidth(subjText)) / 2;
        y = grid.y + grid.height + fm.getHeight();
        offGraphics.drawString(subjText, x, y);

        s = timeText;
        x = Math.min(d.width - fm.stringWidth(s), list.x);
        offGraphics.drawString(s, x, y);

        s = statText;
        x = Math.min(d.width - fm.stringWidth(s), list.x);
        y += fm.getHeight();
        offGraphics.drawString(s, x, y);

        // Copy the off screen buffer to the screen.

        g.drawImage(offImage, 0, 0, this);
    }
}


These are the parameters that have to interact with the JApplet

<applet code="WordSearch.class" width=w height=h>
  <param name="screencolors" value="foreground,background,border">
  <param name="buttoncolors" value="foreground,background">
  <param name="gridcolors" value="foreground,background,found,highlight">
  <param name="listcolors" value="foreground,background,found">
  <param name="screenfont" value="name,style,size">
  <param name="buttonfont" value="name,style,size">
  <param name="gridfont" value="name,style,size">
  <param name="listfont" value="name,style,size">
  <param name="gridsize" value="rows,cols,size">
  <param name="files" value="url,url,url...">
</applet>

解决方法:

遵循一个非常基本的示例…

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;


public class MyWordGame extends JApplet {

    public void init(){
        add(new JButton("Test"));
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        MyWordGame game=new MyWordGame();
        JFrame myFrame=new JFrame("Test");
        myFrame.add(game);
        myFrame.pack();
        myFrame.setVisible(true);
        game.init();

    }

}

您可以将其作为applet或应用程序运行.
但是请记住,如果您的applet与浏览器进行交互,则必须提供一个自定义的AppletContext,并且您可能最终还希望提供一种applet生命周期的管理(如在适当时调用start()/ stop()/ destroy()).

标签:japplet,java,swing,jframe
来源: https://codeday.me/bug/20191009/1881746.html