运行jar文件时不显示图标

时间:2014-07-17 00:39:04

标签: java image swing jbutton embedded-resource

我是Java的初学者,我按照教程编写了这个程序(是的,我是初学者),当我在Eclipse上运行它时,它运行得很好。它在我编码的计算机上运行得很好。但是,如果我将它发送到另一台计算机(只是.jar文件)并运行它,它会失败,因为它找不到图标。这是我所拥有的一切。我正在使用的图标与该程序的所有类文件一起保存在bin文件夹中。出于隐私原因,我用“WORDS”替换了某些行。

我遵循的教程分为两部分:

第1部分 - https://buckysroom.org/videos.php?cat=31&video=18027

第2部分 - https://buckysroom.org/videos.php?cat=31&video=18028

我的主要课程(我称之为苹果,因为教程确实如此)。

import javax.swing.JFrame;

public class apples {
public static void main(String[] args) {
Gui go = new Gui();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(1920,1080);
go.setVisible(true);
}
}

现在我的第二堂课“Gui”:

import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class Gui extends JFrame {

private JButton custom;

public Gui () {
    super("WORDS");
    setLayout(new FlowLayout());

    Icon b = new ImageIcon(getClass().getResource("b.png"));
    custom = new JButton(null, b);
    custom.setToolTipText("WORDS");
    add(custom);

    HandlerClass handler = new HandlerClass();
    custom.addActionListener(handler);
}

private class HandlerClass implements ActionListener {
    public void actionPerformed(ActionEvent event) {
        JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
        JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
        JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
        JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
    }
}
}

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

值得一读Loading Images Using getResource,详细解释这些内容以及从jar中加载图片。

您可以根据图片位置尝试任何一种。

// Read from same package 
ImageIO.read(getClass().getResourceAsStream("b.png"));

// Read from src/images folder
ImageIO.read(getClass().getResource("/images/b.png"))

// Read from src/images folder
ImageIO.read(getClass().getResourceAsStream("/images/b.png"))

Read more...

相关问题