程序不起作用 - NullPointerException

use*_*344 -3 java eclipse runtime-error nullpointerexception

我使用eclipse将我的项目导出为可运行的jar文件,当我尝试运行时没有任何反应,当我使用cmd运行它时,我得到了这个错误.

C:\Users\Enes\Desktop>cmd.exe
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Enes\Desktop>java -jar Game.Jar
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoa
der.java:58)
Caused by: java.lang.NullPointerException
        at scrolls.Resources.createArray(Resources.java:111)
        at scrolls.Player.<init>(Player.java:31)
        at scrolls.Draw.<init>(Draw.java:27)
        at scrolls.Frame.main(Frame.java:18)
        ... 5 more

C:\Users\Enes\Desktop>
Run Code Online (Sandbox Code Playgroud)

当我使用eclipse运行它时,运行正常,没有错误或警告.

这是我的资源文件,似乎在第111行引起了问题

package scrolls;

import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.imgscalr.Scalr;

public class Resources
{
    Map map;
    static BufferedImage[] textures = new BufferedImage[8];
    static BufferedImage[] mapTextures = new BufferedImage[9];
    static BufferedImage texture;
    static BufferedImage[] waterAnimated = new BufferedImage[64];
    static BufferedImage water;
    static BufferedImage icon;
    public static Font f, fs;
    static int imageCounter = 0;

    public Resources()
    {
        map = new Map();
        textures();
        createArray(texture, textures, 32, 1, 8);
        createArray(water, waterAnimated, 32, 64, 1);
        getFont();
        buildMapTextures(textures, mapTextures);
    }

    public static void counter()
    {
        imageCounter++;
        if (imageCounter >= 500)
            imageCounter = 0;
        //System.out.println(imageCounter / 8);
    }

    private void buildMapTextures(BufferedImage[] textures, BufferedImage[] mapTextures)
    {

        for (int i = 0; i <= 7; i++)
        {
            mapTextures[i] = resize(textures[i], 3, 3);
        }
        mapTextures[8] = resize(waterAnimated[2], 3, 3);
    }

    private BufferedImage resize(BufferedImage image, int newW, int newH)
    {
        BufferedImage thumbnail = Scalr.resize(image, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_EXACT, newW, newH, Scalr.OP_ANTIALIAS);
        return thumbnail;
    }

    public static BufferedImage waterAnimation()
    {
        return waterAnimated[imageCounter / 8];
    }

    private void textures()
    {
        try
        {
            texture = ImageIO.read(new File("src/resources/textures.png"));
        } catch (IOException e)
        {
        }

        try
        {
            water = ImageIO.read(new File("src/resources/water.png"));
        } catch (IOException e)
        {
        }

        try
        {
            icon = ImageIO.read(new File("src/resources/icon.png"));
        } catch (IOException e)
        {
        }

    }

    static BufferedImage player()
    {
        BufferedImage player = null;
        try
        {
            player = ImageIO.read(new File("src/resources/player.png"));
        } catch (IOException e)
        {
        }
        return player;
    }

    static void createArray(BufferedImage image, BufferedImage[] images, int size, int rows, int cols)
    {
        BufferedImage temp = image;

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                images[(i * cols) + j] = temp.getSubimage(j * size, i * size, size, size); // line 111
            }
        }
    }

    public static void readLevel(String filename, int[][] level, int part)
    {
        try
        {
            File f = new File("src/resources/levels/" + part + "/" + filename + ".txt");
            FileReader fr = new FileReader(f);
            BufferedReader in = new BufferedReader(fr);
            StringBuilder sb = new StringBuilder();
            byte b = 0;
            while ((b = (byte) in.read()) != -1)
            {
                sb.append("" + ((char) b));
            }
            String str = sb.toString();
            String[] lines = str.split("(\n|\r)+");
            for (int i = 0; i < lines.length; i++)
            {
                for (int j = 0; j < lines[i].length(); j++)
                {
                    level[i][j] = Integer.parseInt("" + lines[i].charAt(j));
                }
            }
            in.close();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private static void getFont()
    {
        try
        {
            f = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream("src/resources/Jet Set.ttf"));
            fs = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream("src/resources/Jet Set.ttf"));
        } catch (Exception e)
        {
            System.out.println(e);
        }
        f = f.deriveFont(22f);
        fs = fs.deriveFont(13f);
    }

}
Run Code Online (Sandbox Code Playgroud)

玩家代码

package scrolls;

import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Transparency;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;

public class Player
{
    static int x, y, dx, dy;
    BufferedImage[] sprites = new BufferedImage[8];
    int rotation = 0;
    int imageCounter = 0;
    public static boolean moving = false;
    static int playerEnergy = 150000;
    static int playerLvl = 1;
    static int playerExp = 3;
    static int expNeeded = (((playerLvl + 1) * playerLvl) * 2);
    static int playerHealth = 100;
    static int playerMana = 100;
    static int mapRow = 6;
    static int mapColumn = 8;
    static int playerRow, playerColumn;

    public Player()
    {
        y = 40;
        x = 700;
        Resources.createArray(Resources.player(), sprites, 66, 1, 8);
    }

    private void changeImage()
    {
        imageCounter++;
        if (imageCounter >= 80)
            imageCounter = 0;
    }

    public void move()
    {
        y = y + dy;
        x = x + dx;
        changeImage();
        playerPosition();
    }

    static void mapPosition()
    {
        if (y < 0)
            playerRow = 0;
        else
            playerRow = (y / 32) + 1;
        if (x < 0)
            playerColumn = 0;
        else
            playerColumn = (x / 32) + 1;
    }

    private void playerPosition()
    {
        if (x >= 817 - 59)
        {
            x = -24;
            mapColumn++;
        }

        if (x <= -25)
        {
            x = 817 - 59;
            mapColumn--;
        }

        if (y <= -25)
        {
            y = 599 - 152 - 41;
            mapRow--;
        }
        if (y >= 599 - 152 - 40)
        {
            y = -24;
            mapRow++;
        }
    }

    public static int playerExp()
    {

        return playerExp;
    }

    public static int getNextExp()
    {
        return expNeeded;
    }

    public static int playerLvl()
    {
        if (playerExp >= expNeeded)
        {
            playerLvl++;
        }
        return playerLvl;
    }

    public static int playerHealth()
    {
        return playerHealth;
    }

    public static int playerMana()
    {
        return playerMana;
    }

    public static int playerEnergy()
    {
        if ((dx != 0) || (dy != 0))
            playerEnergy--;
        if ((dx != 0) && (dy != 0))
            playerEnergy--;

        return playerEnergy;
    }

    public int getX()
    {
        return x;
    }

    public int getY()
    {
        return y;
    }

    public static BufferedImage rotate(BufferedImage image, double angle)
    {
        double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
        int w = image.getWidth(), h = image.getHeight();
        int neww = (int) Math.floor(w * cos + h * sin), newh = (int) Math.floor(h * cos + w * sin);

        GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
        BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
        Graphics2D g = result.createGraphics();

        g.translate((neww - w) / 2, (newh - h) / 2);
        g.rotate(angle, w / 2, h / 2);
        g.drawRenderedImage(image, null);
        g.dispose();

        return result;
    }

    public BufferedImage getPlayerImage()
    {

        roatePlayer();
        int image = animatePlayer();

        double angle = Math.toRadians(rotation);

        if (dy != 0 || dx != 0)
        {
            return rotate(sprites[image], angle);
        }
        return rotate(sprites[0], angle);

    }

    private int animatePlayer()
    {
        return imageCounter / 10;
    }

    private void roatePlayer()
    {
        if (dy > 0)
            rotation = 0;
        if (dy < 0)
            rotation = 180;
        if (dx > 0)
            rotation = -90;
        if (dx < 0)
            rotation = 90;

        if (dy > 0 && dx > 0)
            rotation = -45;
        if (dy > 0 && dx < 0)
            rotation = 45;
        if (dy < 0 && dx < 0)
            rotation = 135;
        if (dy < 0 && dx > 0)
            rotation = -135;
    }

    public void keyPressed(KeyEvent e)
    {
        int key = e.getKeyCode();

        if (key == KeyEvent.VK_A)
        {
            dx = -1;
            rotation = -90;
        }

        if (key == KeyEvent.VK_S)
        {
            dy = 1;
            rotation = 0;
        }

        if (key == KeyEvent.VK_D)
        {
            dx = 1;
            rotation = 90;
        }

        if (key == KeyEvent.VK_W)
        {
            dy = -1;
            rotation = 180;
        }

    }

    public void keyReleased(KeyEvent e)
    {
        int key = e.getKeyCode();

        if (key == KeyEvent.VK_A)
            dx = 0;

        if (key == KeyEvent.VK_S)
            dy = 0;

        if (key == KeyEvent.VK_D)
            dx = 0;

        if (key == KeyEvent.VK_W)
            dy = 0;
    }

}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

我强烈怀疑你是通过假设它们作为文件存在,或者你正在使用适当getResource/ getResourceAsStream调用来加载一些资源(声音,图像),但是你的资源不存在于jar文件中.如果没有看到任何代码或jar文件中的内容,我们无法判断,但是您应该检查加载资源的位置以及您希望找到资源的原因.

哦,你也可能遇到一个套管问题 - 当它从Windows文件系统加载资源时,FOO.PNG即使调用了文件,它也会工作foo.png; 从jar文件加载资源时,情况并非如此.

当然,您应该查看Resources.java第111行和Player.java第31行,以帮助准确确定出现了什么问题(例如,哪个资源出现故障).

编辑:好的,既然我们已经得到了代码,那就完全按照我的建议.这行代码在Resource.player():

player = ImageIO.read(new File("src/resources/player.png"));
Run Code Online (Sandbox Code Playgroud)

...加载player.png期待它成为一个文件的本地文件系统上.你想要的东西:

player = ImageIO.read(Resource.class.getResource("/src/resources/player.png"));
Run Code Online (Sandbox Code Playgroud)

src顺便说一句,在你的jar文件中有一个文件夹是很奇怪的.如果您实际上只是将图像放在reources目录中,您需要:

player = ImageIO.read(Resource.class.getResource("/resources/player.png"));
Run Code Online (Sandbox Code Playgroud)

  • @ user2457344:是的,毕竟这是我从一开始就回答的第一点.请退后一步,找出a)在提出问题之前你可以做出什么诊断; b)你如何发布一个更好的问题(只有*相关*代码); c)如何根据我的答案中的选项检查您的代码以根据我的答案发现问题. (2认同)
  • @ user2457344:在一个单独的问题中询问,只有相关的代码位,以及一个*很多*更具体的细节而不是"它不喜欢我导入我的字体的方式".仔细阅读我之前链接过的两个页面,并在下次提问时牢记这些页面.请注意,如果您提出几个不好的问题,您将被禁止提问. (2认同)