【问题标题】:an exportet jar file won't access resourcesexportet jar 文件不会访问资源
【发布时间】:2013-04-09 12:18:37
【问题描述】:

当我试图打开它时,它找不到资源。 所以,我已经尝试过使用that solution,但我遇到了另一个问题:

Exception in thread "main" java.lang.Error: Unresolved compilation
problem: Cannot make a static reference to the non-static method
getClass() from the type Object
        at Resources.getMainBG(Resources.java:21)
        at Tetris.<init>(Tetris.java:21)
        at Main.main(Main.java:5)

当前代码:

import java.awt.*;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class Resources 
{
    // this class import the breaks's photos into an image array named "images"
    private static Image[] images = new Image[7];
    private static Image[] BG = new Image[3]; // 1=frame,2=pane,3=nextPane


    public static Image getImage(int color){
        if(images[color]==null){
            try{images[color] = new ImageIcon(getClass().getResource("images/block" + color + ".png")).getImage();}
            catch (Exception e){e.printStackTrace();System.exit(1);}}
        return images[color];}

    public static Image getMainBG() {
        if (BG[0] == null)
            BG[0] = new ImageIcon(getClass().getResource("images/MainBG.png")).getImage();
        return BG[0];}

    public static Image getPaneBG(){
        if (BG[1] == null)
            BG[1] = new ImageIcon(getClass().getResource("images/PaneBG.png")).getImage();
        return BG[1];}

    public static Image getNextBG() {
        if (BG[2] == null)
            BG[2] = new ImageIcon(getClass().getResource("images/NextBG.png")).getImage();
        return BG[2];}
}

非常感谢您的帮助!

【问题讨论】:

    标签: java jar resources


    【解决方案1】:

    异常说明了一切 - 代码在您导出时甚至没有编译。此方法无效:

    public static Image getMainBG() {
        if (BG[0] == null)
            BG[0] = new ImageIcon(getClass().getResource("images/MainBG.png")).getImage();
        return BG[0];
    }
    

    您不能像在静态方法中那样调用不合格的getClass()。当然,您可以使用Resources.class

    请注意,您不应该接近异常:您应该在开始打包之前检查您的代码是否已编译

    【讨论】:

      【解决方案2】:

      试试这个:

      Image i = javax.imageio.ImageIO.read(getClass().getResourceAsStream("/images/x.png"));
      

      【讨论】:

        【解决方案3】:

        答案在例外中。 你应该打电话

        Resources.class.getResource(...)
        

        而不是

        getClass().getResource(...)
        

        【讨论】:

          猜你喜欢
          • 2012-04-26
          • 1970-01-01
          • 2011-02-08
          • 2011-01-24
          • 2013-12-07
          • 2015-04-21
          • 2013-07-20
          • 1970-01-01
          相关资源
          最近更新 更多