简体   繁体   English

如何从Eclipse中导出为可运行的JAR文件?

[英]How can I export as Runnable JAR file from eclipse?

When I try to export as a Runnable JAR file, I have no options for 'Launch configuration'. 当我尝试导出为可运行的JAR文件时,“启动配置”没有任何选项。 Why is this? 为什么是这样? I am new to programming, can anyone help me? 我是编程新手,有人可以帮助我吗?

It's a code for the game Snake. 这是Snake游戏的代码。 Do I need a main()? 我需要main()吗?

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import java.util.Random;

import javax.swing.JOptionPane;

@SuppressWarnings("serial")
public class snakeCanvas extends Canvas implements Runnable, KeyListener
{
private final int BOX_HEIGHT = 15;
private final int BOX_WIDTH = 15;
private final int GRID_HEIGHT = 25;
private final int GRID_WIDTH = 25;

private LinkedList<Point> snake;
private Point fruit;
private int direction = Direction.NO_DIRECTION;

private Thread runThread; //allows us to run in the background
private int score = 0;
private String highScore = "";

private Image menuImage = null;
private boolean isInMenu = true;

public void paint(Graphics g)
{
    if (runThread == null)
    {
        this.setPreferredSize(new Dimension(640, 480));
        this.addKeyListener(this);  
        runThread = new Thread(this);
        runThread.start();
    }
    if (isInMenu)
    {
        DrawMenu(g);
        //draw menu
    }
    else
    {
        if (snake == null)
        {
        snake = new LinkedList<Point>();
        GenerateDefaultSnake();
        PlaceFruit();
        }
        if (highScore.equals(""))
        {
            highScore = this.GetHighScore();
            System.out.println(highScore);
        }
        DrawSnake(g);
        DrawFruit(g);
        DrawGrid(g);
        DrawScore(g);
        //draw everything else
    }
}

public void DrawMenu(Graphics g)
{
    if (this.menuImage == null)
    {
        try
        {
            URL imagePath = snakeCanvas.class.getResource("snakeMenu.png");
            this.menuImage = Toolkit.getDefaultToolkit().getImage(imagePath);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    }
    g.drawImage(menuImage, 0, 0, 640, 480, this);

}

public void update(Graphics g)
{
    Graphics offScreenGraphics;
    BufferedImage offscreen = null;
    Dimension d= this.getSize();

    offscreen = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_ARGB);
    offScreenGraphics = offscreen.getGraphics();
    offScreenGraphics.setColor(this.getBackground());
    offScreenGraphics.fillRect(0, 0, d.width, d.height);
    offScreenGraphics.setColor(this.getForeground());
    paint(offScreenGraphics);

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

public void GenerateDefaultSnake()
{
    score = 0;
    snake.clear();

    snake.add(new Point (0,2));
    snake.add(new Point(0,1));
    snake.add(new Point(0,0));
    direction = Direction.NO_DIRECTION;
}

public void Move() //adds a new 'block' at front of snake, deleting the back 'block' to create movement
{
    Point head = snake.peekFirst();  //grab the first item with no problems
    Point newPoint = head;
    switch (direction) {
    case Direction.NORTH:
        newPoint = new Point(head.x, head.y - 1); //vector of -j
        break;
    case Direction.SOUTH:
        newPoint = new Point(head.x, head.y + 1);
        break;
    case Direction.WEST:
        newPoint = new Point(head.x - 1, head.y);
        break;
    case Direction.EAST:
        newPoint = new Point (head.x + 1, head.y);
        break;  
    }


    snake.remove(snake.peekLast()); //delete the last block

    if (newPoint.equals(fruit))
    {
        //the snake hits the fruit
        score+=10;
        Point addPoint = (Point) newPoint.clone(); //creating the end piece upon eating fruit

        switch (direction) {
        case Direction.NORTH:
            newPoint = new Point(head.x, head.y - 1); //vector of -j
            break;
        case Direction.SOUTH:
            newPoint = new Point(head.x, head.y + 1);
            break;
        case Direction.WEST:
            newPoint = new Point(head.x - 1, head.y);
            break;
        case Direction.EAST:
            newPoint = new Point (head.x + 1, head.y);
            break;
        }
        //the movement upon eating fruit
        snake.push(addPoint);
        PlaceFruit();

    }
    else if (newPoint.x < 0 || newPoint.x > (GRID_WIDTH - 1))
    {
        //snake has gone out of bounds - reset game
        CheckScore();
        GenerateDefaultSnake();
        return;
    }
    else if (newPoint.y < 0 || newPoint.y > (GRID_HEIGHT - 1))
    {
        //snake has gone out of bounds - reset game
        CheckScore();
        GenerateDefaultSnake();
        return;
    }
    else if (snake.contains(newPoint))
    {
        //running into your tail - reset game
        CheckScore();
        GenerateDefaultSnake();
        return;
    }

    snake.push(newPoint);
}

public void DrawScore(Graphics g)
{
    g.drawString("Score: " + score, 0, BOX_HEIGHT * GRID_HEIGHT + 15);
    g.drawString("Highscore:" + highScore, 0, BOX_HEIGHT * GRID_HEIGHT + 30);
}

public void CheckScore()
{
    if (highScore.equals(""))
        return;

    if (score > Integer.parseInt((highScore.split(":")[1])))
    {
        String name = JOptionPane.showInputDialog("New highscore. Enter your name!");
        highScore = name + ":" + score;

        File scoreFile = new File("highscore.dat");
        if (!scoreFile.exists())
        {

            try {
                scoreFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileWriter writeFile = null;
        BufferedWriter writer = null;
        try
        {
            writeFile = new FileWriter(scoreFile);
            writer = new BufferedWriter(writeFile);
            writer.write(this.highScore);
        }
        catch (Exception e)
        {
        }
        finally
        {
            try
        {
            if (writer != null)
                writer.close();
        }
        catch (Exception e) {}
        }
    }
}

public void DrawGrid(Graphics g)
{
    //drawing the outside rectangle
    g.drawRect(0, 0, GRID_WIDTH * BOX_WIDTH, GRID_HEIGHT * BOX_HEIGHT);
    //drawing the vertical lines
    for (int x = BOX_WIDTH; x < GRID_WIDTH * BOX_WIDTH; x+=BOX_WIDTH)
    {
        g.drawLine(x, 0, x, BOX_HEIGHT * GRID_HEIGHT);
    }
    //drawing the horizontal lines
    for (int y = BOX_HEIGHT; y < GRID_HEIGHT * BOX_HEIGHT; y+=BOX_HEIGHT)
    {
        g.drawLine(0,  y,  GRID_WIDTH * BOX_WIDTH, y);
    }
}

public void DrawSnake(Graphics g)
{
    g.setColor(Color.ORANGE);
    for (Point p : snake)
    {
        g.fillRect(p.x * BOX_WIDTH, p.y * BOX_HEIGHT, BOX_WIDTH, BOX_HEIGHT);
    }
    g.setColor(Color.BLACK);
}

public void DrawFruit(Graphics g)
{
    g.setColor(Color.RED);
    g.fillOval(fruit.x * BOX_WIDTH, fruit.y * BOX_HEIGHT, BOX_WIDTH, BOX_HEIGHT);
    g.setColor(Color.BLACK);
}

public void PlaceFruit()
{
    Random rand = new Random();
    int randomX = rand.nextInt(GRID_WIDTH);
    int randomY = rand.nextInt(GRID_HEIGHT);
    Point randomPoint = new Point(randomX, randomY);
    while (snake.contains(randomPoint))  //If the fruit happens to spawn on the snake, it will change position
    {
        randomX= rand.nextInt(GRID_WIDTH);
        randomY= rand.nextInt(GRID_HEIGHT);
        randomPoint = new Point(randomX, randomY);
    }
    fruit = randomPoint;
}

@Override
public void run() {
    while (true)
    {
        repaint(); 
        //runs indefinitely (CONSTANTLY LOOPS)
        if (!isInMenu)
            Move();

                     //Draws grid, snake and fruit

        //buffer to slow down the snake
        try
        {
            Thread.currentThread();
            Thread.sleep(100);

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}

public String GetHighScore()
{
    FileReader readFile = null;
    BufferedReader reader = null;
    try
    {
    readFile = new FileReader("highscore.dat");
    reader = new BufferedReader(readFile);
    return reader.readLine();

}
    catch (Exception e)
    {
        return "Nobody:0";
    }
    finally
    {
        try{
            if (reader != null)
                reader.close();
        } catch (IOException e){
            e.printStackTrace();
        }
    }   
}

@Override
public void keyPressed(KeyEvent e) {
    switch (e.getKeyCode())
    {
    case KeyEvent.VK_UP:
        if (direction != Direction.SOUTH)
            direction = Direction.NORTH;
        break;
    case KeyEvent.VK_DOWN:
        if (direction != Direction.NORTH)
            direction = Direction.SOUTH;
        break;
    case KeyEvent.VK_RIGHT:
        if (direction != Direction.WEST)
            direction = Direction.EAST;
        break;
    case KeyEvent.VK_LEFT:
        if (direction != Direction.EAST)
        direction = Direction.WEST;
        break;
    case KeyEvent.VK_ENTER:
        if (isInMenu)
        {
            isInMenu = false;
            repaint();
        }
        break;
    case KeyEvent.VK_ESCAPE:
        isInMenu = true;
        break;
    }

}

@Override
public void keyReleased(KeyEvent e) {


}

@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}

} }

Basically, you need a Run configuration that was already used to execute your Java application to have a runnable jar file. 基本上,您需要一个已经用于执行Java应用程序的Run配置,以使其具有可运行的jar文件。 This is used to select the correct starting point of the program. 这用于选择正确的程序起点。

If you have executed your Java application using the Run command (either from the Run menu or the toolbar), a Run configuration was created that executes. 如果使用“运行”命令(从“运行”菜单或工具栏)执行了Java应用程序,则会创建一个运行配置并执行。 However, judging from your question, you have not done so, as you have no entrypoint defined for your application. 但是,从您的问题来看,您尚未这样做,因为您没有为应用程序定义入口点。

For that java uses a static main method with predefined parameters , and any Java class that has such a method can be executed. 为此,java使用带有预定义参数静态main方法 ,并且可以执行具有这种方法的任何Java类。 After you have successfully executed your application, it can be started, and then the created run configuration can be used to export a jar file. 成功执行应用程序后,可以启动它,然后可以使用创建的运行配置导出jar文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM