【问题标题】:i am not able to get the images read in java for exporting it as JAR我无法在 java 中读取图像以将其导出为 JAR
【发布时间】:2015-10-15 14:55:25
【问题描述】:

这段代码抛出一个NullPointerException,我不知道为什么。

try {
    imageIcon = new ImageIcon(ImageIO.read(new File("res/Background.png")));
    backgroundImage = imageIcon.getImage();
    signIn = new MyButton("SignIn", ImageIO.read(new File("res/SignIn.png")), ImageIO.read(new File("res/SignInHover.png")));
    signUp = new MyButton("SignUp", ImageIO.read(new File("res/SignUp.png")), ImageIO.read(new File("res/SignUpHover.png")));
    back = new MyButton("Back", ImageIO.read(new File("res/Back.png")), ImageIO.read(new File("res/BackHover.png")));
    exit = new MyButton("Exit", ImageIO.read(new File("res/Exit.png")), ImageIO.read(new File("res/ExitHover.png")));
} catch(IOException e) {
    JOptionPane.showMessageDialog(null, "");
}

res/ 是项目根目录中的一个源文件夹,其中包含这段代码中使用的所有图像,但我无法让它工作。我试过使用getClass().getResource()(它在 Eclipse 内部工作,但不能从 .jar 文件中工作)和getClass().getResourceAsStream()(它抛出一个异常,告诉输入流为空)但无济于事。

P.S.:MyButton 是一个用户定义的类,它扩展了JButton 并有一个构造函数MyButton(String, final BufferedImage, final BufferedImage)

【问题讨论】:

  • 可能SignIn.png 像其他资产一样位于/res 目录中?
  • 是的,每个 PNG 都在 /res 中,与 src 处于同一级别,并且是项目的源文件夹
  • 那么你为什么要打开/SignIn.png,而不是res/SignIn.png
  • 实际上这是我处理代码的错误。我正在尝试各种可能的方式来访问它。但他们都没有工作。错误来自 ImageIcon 行..

标签: java swing executable-jar


【解决方案1】:

毕竟我只是在我的源(即 res)文件夹下创建了 images 文件夹。并使用方法

ImageIO.read(getClass().getResource("/images/SignIn.png"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-26
    • 2011-08-28
    • 1970-01-01
    • 2011-06-19
    • 2023-04-06
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多