【问题标题】:Java - Export to JAR file in eclipse with resources (images and audio files)Java - 使用资源(图像和音频文件)在 Eclipse 中导出到 JAR 文件
【发布时间】:2017-02-01 04:04:00
【问题描述】:

我在 linux Ubuntu 上使用 eclipse,我有这段代码用于加载图像并将其设置为我的一个 JPanel 中的背景:

public class MenuState extends JPanel implements ActionListener {

private static final long serialVersionUID = 1L;
private GameStateManager gsm;
private int width;
private int height;

public MenuState(GameStateManager gsm)
{
    this.gsm = gsm;
    width = gsm.getWidth();
    height = gsm.getHeight();
    SizeManager sm = new SizeManager();
    this.setLayout(new BorderLayout());
    sm.set_size(this, width, height);
}

public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    BufferedImage background_image;
    try {
        background_image = ImageIO.read(new File("src/res/img/menu_background.png"));
        g.drawImage(background_image, 0, 0, width, height, null);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void actionPerformed(ActionEvent e) {
}

它只在 Eclipse 中有效。当我将其导出到 jar 文件或可运行的 jar 文件时,程序不显示图像。我也试过用

this.getClass().getResource()

和类似的代码,但它在 Eclipse 中不起作用。但我可能做错了什么。

我在另一个类中也有这段代码来播放音频:

public class AudioManager {

private Clip clip;

public void play(String audio_name, boolean repeat)
{   
    try {
        File audioFile = new File(audio_name);
        AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
        AudioFormat format = audioStream.getFormat();
        DataLine.Info info = new DataLine.Info(Clip.class, format);
        clip = (Clip) AudioSystem.getLine(info);
        clip.open(audioStream);
        if(repeat)
        {
            clip.loop(clip.LOOP_CONTINUOUSLY);
        }
        clip.start();

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

public void stop()
{
    clip.stop();
}

它在 Eclipse 中播放音频,但在我导出项目后不播放。

我想 File 只适用于磁盘上的文件,而不适用于 jar 文件中的文件,但这是我让它在 eclipse 中工作的唯一方法。

那么,我该怎么办?

还有一个问题: 在 Eclipse 中播放的声音有延迟,我对其进行了改进,增加了 Eclipse 的可用内存,但在加载程序和通过单击 JButton 更改 JFrame 中的 JPanel 时几乎没有延迟。

感谢您的建议。

【问题讨论】:

    标签: java eclipse image audio jar


    【解决方案1】:

    你在getResource 方法中加入了什么字符串? 使用getResourcegetResourceAsStream 时,必须指定包路径。如果您的文件在“com.test.example”包中,则必须输入getResource("/com/test/example/my_file.png")

    因此,对于您的背景图片,您必须使用以下内容加载图片:

    background_image = ImageIO.read(this.getClass().getResource("/res/img/menu_background.png"));
    

    你应该对你的音频文件做同样的事情。

    我还建议您在 paintComponent 方法之外加载图像。否则,每次重新绘制面板时,都会重新加载图像。

    【讨论】:

    • 谢谢,我认为我可以使用在 File 中使用的相同路径,但对于 getResource(),我必须删除 /src。对于 eclipse 中的音频滞后有什么建议吗?
    • 不客气。我对 Eclipse 中的音频滞后一无所知,我从未使用过它,所以我无法为您提供帮助。我认为您应该从您的角度进行一些调查,并创建一个专门针对此问题的新线程。
    猜你喜欢
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 2017-07-31
    • 2011-06-19
    • 1970-01-01
    相关资源
    最近更新 更多