【发布时间】: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