当前位置: 代码迷 >> Java相关 >> [原创]我了个小游戏,但有个问题想问问大家
  详细解决方案

[原创]我了个小游戏,但有个问题想问问大家

热度:109   发布时间:2006-03-31 20:43:00.0
[原创]我了个小游戏,但有个问题想问问大家

代码如下,做的粗糙了些,不好意思啊,没做过游戏。
我想问的是,我生成了一个可执行的.jar文件,里面也包含了需要加载的图片,可是如果文件夹里面如果没有图片那么在运行过程中图片就不显示,为什么呢?
我把文件打包大家自己运行以下就知道了,想要运行成功的话图片(liandluo.gif)就必须和程序放在一个目录下,而放在jar包里就不行,想不通。。。。。

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Fanying extends JFrame implements MouseListener,ActionListener
{
public static void main(String[] args)
{
Fanying f = new Fanying();
}
Timer timer;
int score;
JLabel img[] = new JLabel[4];
JLabel lb1;

public Fanying()
{
super("看看你的敏捷度!");
Container c = getContentPane();
c.setLayout(null);
lb1 = new JLabel("点击下面的图片!!");

lb1.setFont(new Font("仿宋",Font.BOLD,14));
lb1.setForeground(Color.red);
lb1.setSize(190,40);
c.add(lb1);

ImageIcon icon1 = new ImageIcon("liandluo.gif");
for(int i=0; i<4; i++)
{
img[i] = new JLabel(icon1);
img[i].setSize(80,80);
img[i].setLocation((50 + i*106),150);
img[i].setVisible(true);
img[i].addMouseListener(this);
c.add(img[i]);

}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,400);
setVisible(true);
score = 0;
timer = new Timer(200,this);
timer.start();
}
public void actionPerformed(ActionEvent e)
{

if(e.getSource() == timer)
{

int i = 0;
i = (int)(Math.random()*4);
img[i].setVisible(true);
//img[i].setVisible(false);

}
if(e.getSource() == timer)
{
int j = 0;
j = (int)(Math.random()*4);
img[j].setVisible(false);
}
}


public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseClicked(MouseEvent e)
{
for(int i=0; i<4; i++)
{
if(e.getSource() == img[i])
{
score = score + 1;
lb1.setText("你点到了 " + score + " 下!!");
img[i].setVisible(false);
//int k;
//k = (int)(Math.random()*4);
//img[k].setVisible(true);
}

}
}
}


搜索更多相关的解决方案: 小游戏  

----------------解决方案--------------------------------------------------------
我以前也遇到过这样的问题
classpath只是找类文件的吧
找不到其他的文件
所以其他的还要在相同的目录中找啊

----------------解决方案--------------------------------------------------------
谢谢楼上的,大家还有别的解释吗?
斑竹怎么说?
----------------解决方案--------------------------------------------------------
图片是可以放在jar 文件里的,你可以放在和你的class文件一个目录下,也可以新建一个文件夹放在里面
如果是和你和class文件一个目录下,你就必须得到图片文件的URL地址才能显示
对于文件里面的文件的URL地址,可以用以下方法得到
假设你的图片名叫xx.gif
那么你可以用,
URL url=this.getClass().getResource("xx.gif");
然后你就可以用这个URL构造一个图片了
Image image=this.getToolkit().createImage(url);

----------------解决方案--------------------------------------------------------
thank you
----------------解决方案--------------------------------------------------------
ImageIcon icon1 = new ImageIcon("liandluo.gif");
改成:


ImageIcon icon1 = new ImageIcon(包名.Fanying.class.getResource("liandluo.gif"));
把图片文件放到Fanying所在文件夹中做成.jar文件
也是可以的应该~
----------------解决方案--------------------------------------------------------
  相关解决方案