由于某种原因,以下代码无法正确导入图像并显示它。如果我注释掉绘图部分,它会起作用。我不知道为什么。
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class BoardBuild extends JPanel{
String picPath = "pictures/";
String[] fileName = {"board.png"};
ClassLoader cl = BoardBuild.class.getClassLoader();
URL imgURL[] = new URL[1];
Toolkit tk = Toolkit.getDefaultToolkit();
Image imgBG;
public BoardBuild() throws Exception {
for (int x = 0; x < 1; x++)
imgURL[x] = cl.getResource(picPath + fileName[x]);
imgBG = tk.createImage(imgURL[0]);
}
public void paintComponent(Graphics g) {
g.drawImage(imgBG, 0, 0, 150,150 , 0, 0,73, 73, this);
}
}
因为它是 Eclipse,所以图片在文件夹中workspace\BoardMaskTest\src\pictures
。我将不胜感激。