Java 将程序转换为小程序

Java 将程序转换为小程序,java,applet,Java,Applet,您好,我和一位朋友想在我们的网站上添加一个滑块益智游戏,并用于C的教育目的。我们找到了一个源代码,但它是一个程序,而不是小程序。我们如何将其转换为工作小程序? 节目是 import javax.swing.JFrame; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; /////////////////////////////////////////////

您好,我和一位朋友想在我们的网站上添加一个滑块益智游戏,并用于C的教育目的。我们找到了一个源代码,但它是一个程序,而不是小程序。我们如何将其转换为工作小程序? 节目是

import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
///////////////////////////////////////////// class SlidePuzzle
class SlidePuzzle {
    //============================================= method main
    public static void main(String[] args) {
        JFrame window = new JFrame("Slide Puzzle");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setContentPane(new SlidePuzzleGUI());
        window.pack();  // finalize layout
        window.show();  // make window visible
        window.setResizable(false);
    }//end main
}//endclass SlidePuzzle




/////////////////////////////////////////////////// class SlidePuzzleGUI
// This class contains all the parts of the GUI interface
class SlidePuzzleGUI extends JPanel {
    //=============================================== instance variables
    private GraphicsPanel    _puzzleGraphics;
    private SlidePuzzleModel _puzzleModel = new SlidePuzzleModel();
    //end instance variables


    //====================================================== constructor
    public SlidePuzzleGUI() {
        //--- Create a button.  Add a listener to it.
        JButton newGameButton = new JButton("New Game");
        newGameButton.addActionListener(new NewGameAction());

        //--- Create control panel
        JPanel controlPanel = new JPanel();
        controlPanel.setLayout(new FlowLayout());
        controlPanel.add(newGameButton);

        //--- Create graphics panel
        _puzzleGraphics = new GraphicsPanel();

        //--- Set the layout and add the components
        this.setLayout(new BorderLayout());
        this.add(controlPanel, BorderLayout.NORTH);
        this.add(_puzzleGraphics, BorderLayout.CENTER);
    }//end constructor


    //////////////////////////////////////////////// class GraphicsPanel
    // This is defined inside the outer class so that
    // it can use the outer class instance variables.
    class GraphicsPanel extends JPanel implements MouseListener {
        private static final int ROWS = 3;
        private static final int COLS = 3;

        private static final int CELL_SIZE = 80; // Pixels
        private Font _biggerFont;


        //================================================== constructor
        public GraphicsPanel() {
            _biggerFont = new Font("SansSerif", Font.BOLD, CELL_SIZE/2);
            this.setPreferredSize(
                   new Dimension(CELL_SIZE * COLS, CELL_SIZE*ROWS));
            this.setBackground(Color.black);
            this.addMouseListener(this);  // Listen own mouse events.
        }//end constructor


        //=======================================x method paintComponent
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (int r=0; r<ROWS; r++) {
                for (int c=0; c<COLS; c++) {
                    int x = c * CELL_SIZE;
                    int y = r * CELL_SIZE;
                    String text = _puzzleModel.getFace(r, c);
                    if (text != null) {
                        g.setColor(Color.gray);
                        g.fillRect(x+2, y+2, CELL_SIZE-4, CELL_SIZE-4);
                        g.setColor(Color.black);
                        g.setFont(_biggerFont);
                        g.drawString(text, x+20, y+(3*CELL_SIZE)/4);
                    }
                }
            }
        }//end paintComponent


        //======================================== listener mousePressed
        public void mousePressed(MouseEvent e) {
            //--- map x,y coordinates into a row and col.
            int col = e.getX()/CELL_SIZE;
            int row = e.getY()/CELL_SIZE;

            if (!_puzzleModel.moveTile(row, col)) {
                // moveTile moves tile if legal, else returns false.
                Toolkit.getDefaultToolkit().beep();
            }

            this.repaint();  // Show any updates to model.
        }//end mousePressed


        //========================================== ignore these events
        public void mouseClicked (MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseEntered (MouseEvent e) {}
        public void mouseExited  (MouseEvent e) {}
    }//end class GraphicsPanel

    ////////////////////////////////////////// inner class NewGameAction
    public class NewGameAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            _puzzleModel.reset();
            _puzzleGraphics.repaint();
        }
    }//end inner class NewGameAction

}//end class SlidePuzzleGUI






class SlidePuzzleModel {
    private static final int ROWS = 3;
    private static final int COLS = 3;

    private Tile[][] _contents;  // All tiles.
    private Tile     _emptyTile; // The empty space.


    //================================================= constructor
    public SlidePuzzleModel() {
        _contents = new Tile[ROWS][COLS];
        reset();               // Initialize and shuffle tiles.
    }//end constructor


    //===================================================== getFace
    // Return the string to display at given row, col.
    String getFace(int row, int col) {
        return _contents[row][col].getFace();
    }//end getFace


    //======================================================= reset
    // Initialize and shuffle the tiles.
    public void reset() {
        for (int r=0; r<ROWS; r++) {
            for (int c=0; c<COLS; c++) {
                _contents[r][c] = new Tile(r, c, "" + (r*COLS+c+1));
            }
        }
        //--- Set last tile face to null to mark empty space
        _emptyTile = _contents[ROWS-1][COLS-1];
        _emptyTile.setFace(null);

        //-- Shuffle - Exchange each tile with random tile.
        for (int r=0; r<ROWS; r++) {
            for (int c=0; c<COLS; c++) {
                exchangeTiles(r, c, (int)(Math.random()*ROWS)
                                  , (int)(Math.random()*COLS));
            }
        }
    }//end reset


    //==================================================== moveTile
    // Move a tile to empty position beside it, if possible.
    // Return true if it was moved, false if not legal.
    public boolean moveTile(int r, int c) {
        //--- It's a legal move if the empty cell is next to it.
        return checkEmpty(r, c, -1, 0) || checkEmpty(r, c, 1, 0)
            || checkEmpty(r, c, 0, -1) || checkEmpty(r, c, 0, 1);
    }//end moveTile


    //================================================== checkEmpty
    // Check to see if there is an empty position beside tile.
    // Return true and exchange if possible, else return false.
    private boolean checkEmpty(int r, int c, int rdelta, int cdelta) {
        int rNeighbor = r + rdelta;
        int cNeighbor = c + cdelta;
        //--- Check to see if this neighbor is on board and is empty.
        if (isLegalRowCol(rNeighbor, cNeighbor) 
                  && _contents[rNeighbor][cNeighbor] == _emptyTile) {
            exchangeTiles(r, c, rNeighbor, cNeighbor);
            return true;
        }
        return false;
    }//end checkEmpty


    //=============================================== isLegalRowCol
    // Check for legal row, col
    public boolean isLegalRowCol(int r, int c) {
        return r>=0 && r<ROWS && c>=0 && c<COLS;
    }//end isLegalRowCol


    //=============================================== exchangeTiles
    // Exchange two tiles.
    private void exchangeTiles(int r1, int c1, int r2, int c2) {
        Tile temp = _contents[r1][c1];
        _contents[r1][c1] = _contents[r2][c2];
        _contents[r2][c2] = temp;
    }//end exchangeTiles


    //=================================================== isGameOver
    public boolean isGameOver() {
        for (int r=0; r<ROWS; r++) {
            for (int c=0; c<ROWS; c++) {
                Tile trc = _contents[r][c];
                return trc.isInFinalPosition(r, c);
            }
        }

        //--- Falling thru loop means nothing out of place.
        return true;
    }//end isGameOver
}//end class SlidePuzzleModel



////////////////////////////////////////////////////////// class Tile
// Represents the individual "tiles" that slide in puzzle.
class Tile {
    //============================================ instance variables
    private int _row;     // row of final position
    private int _col;     // col of final position
    private String _face;  // string to display 
    //end instance variables


    //==================================================== constructor
    public Tile(int row, int col, String face) {
        _row = row;
        _col = col;
        _face = face;
    }//end constructor


    //======================================================== setFace
    public void setFace(String newFace) {
        _face = newFace;
    }//end getFace


    //======================================================== getFace
    public String getFace() {
        return _face;
    }//end getFace


    //=============================================== isInFinalPosition
    public boolean isInFinalPosition(int r, int c) {
        return r==_row && c==_col;
    }//end isInFinalPosition
}//end class Tile
import javax.swing.JFrame;
导入java.awt.*;
导入java.awt.event.*;
导入javax.swing.*;
导入javax.swing.event.*;
/////////////////////////////////////////////类SlidePuzzle
类SlidePuzzle{
//==================================================================================方法主
公共静态void main(字符串[]args){
JFrame窗口=新的JFrame(“幻灯片拼图”);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(新的SlidePuzzleGUI());
window.pack();//完成布局
window.show();//使窗口可见
window.setresizeable(false);
}//端干管
}//endclass SlidePuzzle
///////////////////////////////////////////////////类SlidePuzzleGUI
//此类包含GUI界面的所有部分
类SlidePuzzleGUI扩展了JPanel{
//================================================================实例变量
私有图形spanel\u puzzleGraphics;
私有SlidePuzzleModel_puzzleModel=新SlidePuzzleModel();
//结束实例变量
//=================================================================================构造函数
公共幻灯片puzzlegui(){
//---创建一个按钮。向其添加一个侦听器。
JButton newGameButton=新JButton(“新游戏”);
addActionListener(newNewGameAction());
//---创建控制面板
JPanel controlPanel=新的JPanel();
setLayout(新的FlowLayout());
控制面板。添加(新游戏按钮);
//---创建图形面板
_puzzleGraphics=新的GraphicsPanel();
//---设置布局并添加组件
此.setLayout(新的BorderLayout());
添加(控制面板,BorderLayout.NORTH);
添加(_puzzleGraphics,BorderLayout.CENTER);
}//端构造函数
////////////////////////////////////////////////类平面
//这是在外部类中定义的,以便
//它可以使用外部类实例变量。
类GraphicsPanel扩展JPanel实现MouseListener{
私有静态最终整数行=3;
专用静态最终int COLS=3;
私有静态最终整数单元格\u SIZE=80;//像素
私人字体(biggerFont);;
//===============================================================================构造函数
公共图形spanel(){
_biggerFont=新字体(“SansSerif”,Font.BOLD,单元格大小/2);
此.setPreferredSize(
新维度(单元格大小*列,单元格大小*行);
这个.背景(颜色.黑色);
this.addMouseListener(this);//侦听自己的鼠标事件。
}//端构造函数
//================================================================x方法组件
公共组件(图形g){
超级组件(g);

对于(int r=0;r我担心这里的简单摘要涉及的内容太多了,除了让您阅读关于如何创建GUI和JApplets,然后重新编写或修改此代码以成为小程序之外

至于你做错了什么

  • 您有任何错误或例外吗
  • 你的代码目前在做什么
  • 您是否有任何调试代码可以帮助您检查程序运行时的状态
  • 您似乎还没有向小程序的contentPane添加任何内容,似乎正在尝试直接调用
    init()
    方法。这表明您还没有看过教程——在来到这里之前,您应该先这样做
我可以说,您需要一个扩展JApplet的类,您不需要或没有main方法,您需要使GUI面向创建JPanel,您通常会在GUI类的构造函数中构建GUI,然后将其添加到applet的
init()中的JApplet内容窗格中
method,但细节太重要了,不能忽略。请再次阅读教程,如果您遇到困难并有具体的可回答问题,请返回

请注意,通常情况下,您希望避免使用“借用”的代码,尤其是在游戏早期。最好先研究代码,然后使用从下载的代码中获得的想法从头开始编写自己的程序

想在我们的网站上添加一款滑块益智游戏

不要对代码进行任何转换,而是将类添加到一个Jar中,编写一个JNLP文件来启动它(类似于applet HTML),并为用户提供一个播放滑块拼图的按钮

当(/if)用户决定单击链接时,将使用直接从站点下载并启动应用程序


这是一种可以提供更好的用户体验、更少部署问题的方法。

hmm我试过了,但是我们在uni的课程和教程没有太大帮助。我将学习代码并尝试从头开始编写一个应用程序。如果我遇到问题,我将写一篇新文章。。谢谢你提供的信息。@Amethyst:听起来是个不错的计划。B真幸运!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.awt.*;
import java.util.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
/////////////////////////////////;////////////////// class SlidePuzzleGUI
// This class contains all the parts of the GUI interface
class SlidePuzzleGUI  extends JApplet {
    //=============================================== instance variables
    private GraphicsPanel    _puzzleGraphics;
    private SlidePuzzleModel _puzzleModel = new SlidePuzzleModel();
    //end instance variables
 JPanel controlPanel = new JPanel();

    //====================================================== constructor
    public SlidePuzzleGUI() {
        //--- Create a button.  Add a listener to it.
        JButton newGameButton = new JButton("New Game");
        newGameButton.addActionListener(new NewGameAction());

        //--- Create control panel

        controlPanel.setLayout(new FlowLayout());
        controlPanel.add(newGameButton);

        //--- Create graphics panel
        _puzzleGraphics = new GraphicsPanel();

        //--- Set the layout and add the components
        this.setLayout(new BorderLayout());
        this.add(controlPanel, BorderLayout.NORTH);
        this.add(_puzzleGraphics, BorderLayout.CENTER);
    }//end constructor


    //////////////////////////////////////////////// class GraphicsPanel
    // This is defined inside the outer class so that
    // it can use the outer class instance variables.
    class GraphicsPanel extends JPanel implements MouseListener {
        private static final int ROWS = 3;
        private static final int COLS = 3;

        private static final int CELL_SIZE = 80; // Pixels
        private Font _biggerFont;


        //================================================== constructor
        public GraphicsPanel() {
            _biggerFont = new Font("SansSerif", Font.BOLD, CELL_SIZE/2);
            this.setPreferredSize(
                   new Dimension(CELL_SIZE * COLS, CELL_SIZE*ROWS));
            this.setBackground(Color.black);
            this.addMouseListener(this);  // Listen own mouse events.
        }//end constructor


        //=======================================x method paintComponent
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (int r=0; r<ROWS; r++) {
                for (int c=0; c<COLS; c++) {
                    int x = c * CELL_SIZE;
                    int y = r * CELL_SIZE;
                    String text = _puzzleModel.getFace(r, c);
                    if (text != null) {
                        g.setColor(Color.gray);
                        g.fillRect(x+2, y+2, CELL_SIZE-4, CELL_SIZE-4);
                        g.setColor(Color.black);
                        g.setFont(_biggerFont);
                        g.drawString(text, x+20, y+(3*CELL_SIZE)/4);
                    }
                }
            }
        }//end paintComponent


        //======================================== listener mousePressed
        public void mousePressed(MouseEvent e) {
            //--- map x,y coordinates into a row and col.
            int col = e.getX()/CELL_SIZE;
            int row = e.getY()/CELL_SIZE;

            if (!_puzzleModel.moveTile(row, col)) {
                // moveTile moves tile if legal, else returns false.
                Toolkit.getDefaultToolkit().beep();
            }

            this.repaint();  // Show any updates to model.
        }//end mousePressed


        //========================================== ignore these events
        public void mouseClicked (MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseEntered (MouseEvent e) {}
        public void mouseExited  (MouseEvent e) {}
    }//end class GraphicsPanel

    ////////////////////////////////////////// inner class NewGameAction
    public class NewGameAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            _puzzleModel.reset();
            _puzzleGraphics.repaint();
        }
    }//end inner class NewGameAction
 public void init() { System.out.println("Applet initializing");
SlidePuzzleGUI d = new SlidePuzzleGUI();
controlPanel.add(d);
}
public void start() {
System.out.println("Applet starting");
}
public void stop() {
System.out.println("Applet stopping");
}
public void destroy() {
System.out.println("Applet destroyed");
}
public static void main(String args[]){
JFrame frame = new JFrame("Code Converter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SlidePuzzleGUI a = new SlidePuzzleGUI();
a.init();

frame.setContentPane(new SlidePuzzleGUI());
frame.pack();
frame.show();

}//end class SlidePuzzleGUI
}