在Java资源文件夹中插入图像
我有一个数据库WAMP
,在该数据库中,尽管有其他字段,但我可以插入名称,后跟图像的扩展名,例如"imagen1.jpg"
。
我正在做的程序是用Java
和SQL
为句子编写的,我正在使用Netbeans的IDE来完成。
我有一个名为"Imagenes.java"
的类型,在该类型中,我选择图像的路径,以这种方式将其插入我的Jpanel
或Jlabel
public class Imagenes extends javax.swing.JPanel {
String path;
ImageIcon imag;
public Imagenes(int width,int height,String path)
{
this.path=path;
this.setSize(width,height);
}
@Override
public void paint(Graphics graph)
{
Dimension tam = getSize();
if (imag!=null)
graph.drawImage(imag.getImage(),0,0,tam.width, tam.height, null);
else
{
ImageIcon imagenFondo = new ImageIcon(getClass().getResource(path));
graph.drawImage(imagenFondo.getImage(),0,0,tam.width, tam.height, null);
}
setOpaque(false);
super.paintComponent(graph);
}
}
我插入的所有图像都已保存在名为"resources"
的文件夹中。
因此,我想在"resources"
文件夹中添加从"fileChooser"
拾取的计算机中的图像。
我已经尝试了一千种方法,把完整的路线,没有办法为文件夹被识别。但是,
复制源文件夹中的图像。
我尝试过像'\\resources\\imagen1.jpg'
这样的路由类型,是特定于Java的,但它没有正确地选择它。但如果我这样做了
路线字符串的打印,这是正确的。
我做错了什么
# 1 楼答案
我如何使用它保存在资源文件夹中
# 2 楼答案
如果您使用
ImageIcon(path)
而不是ImageIcon(getClass().getResource(path))
。您可能想试试"src/resources/imagen1.jpg"
。Netbeans将从ProjectRoot进行搜索。所以只要输入"resources/imagen1.jpg"
,就不会找到它。您需要添加src
当您使用
ImageIcon(getClass().getResource(path));
时,程序将尝试在build
目录中的classes
目录中查找图像。如果将resources目录放在classes
目录中,那么使用ImageIcon(getClass().getResource(path))
应该可以在上面的场景中,您的
path
将是"resources/imagen.jpg"