我遇到了无法通过 Java 找到图像的问题。我和我的朋友正在做一个项目,我们做了完全相同的事情。我已经更改了图像位置的路径,甚至将图像拖放到 Eclipse 中。然而,我没有运气。这是我的代码:
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MapArray {
static JPanel[][] tiles = new JPanel[30][29];
static String[][] images = new String[30][30];
final static int SIZE = 30;
static int place=0;
public MapArray(){
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Map.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public static void setMap(){
try {
String a = getFileContents("C:\\Users\\*****\\workspace\\Pokemon\\src\\map1.txt");
for(int x=0; x<29; x++){
for(int y=0; y<30; y++){
images[x][y]=a.substring(0,a.indexOf(" "));
a=a.substring(a.indexOf(" ")+1);
System.out.println(images[x][y]);
}
}
} catch (Exception e) {
System.out.println("y u no work :(");
}
}
public static String getFileContents(String fileName) throws Exception {
File theFile = new File(fileName);
byte[] bytes = new byte[(int) theFile.length()];
InputStream in = new FileInputStream(theFile);
int m = 0, n = 0;
while (m < bytes.length) {
n = in.read(bytes, m, bytes.length - m);
m += n;
}
in.close();
return new String(bytes);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setMap();
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(30, 29, 0, 0));
for (int i = 0; i < 29; i++) {
for (int j = 0; j < 29; j++) {
tiles[i][j] = new JPanel(new GridLayout());
tiles[i][j].add(new JLabel(
createImageIcon("C:\\Users\\*****\\workspace\\Pokemon\\src\\tile"+"-"+images[i][j]+".png")));
frame.add(tiles[i][j]);
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
我尝试放入完整图像路径的所有方法都不起作用。另外,任何人都可以提供相对路径的帮助吗?我和我的朋友将在多台计算机之间共享代码,因此非专用于我们工作区所在位置的相对路径会很棒。谢谢!