Java 我能';t显示文件中的图像(paintComponent)

Java 我能';t显示文件中的图像(paintComponent),java,paintcomponent,Java,Paintcomponent,显示文件中的图像时出现问题: public class Drawing extends JPanel { public void paintComponent(Graphics g) { //g.setColor(Color.ORANGE); //g.fillRect(20, 50, 100, 100); Image picture = new ImageIcon("test.jpg").getImage(); g.

显示文件中的图像时出现问题:

public class Drawing extends JPanel
{
    public void paintComponent(Graphics g)
    {
        //g.setColor(Color.ORANGE);
        //g.fillRect(20, 50, 100, 100);
        Image picture = new ImageIcon("test.jpg").getImage();
        g.drawImage(picture, 3, 4, this);
    }
    public static void main(String[] args) 
    {
    Drawing gui1 = new Drawing();
    JFrame frame = new JFrame();
    frame.setSize(300, 300);
    frame.setVisible(true);
    frame.add(gui1);
    frame.repaint();
    }
}
它应该很简单。我将文件测试放在文件夹中,文件夹中有class
绘图
。 我不知道我做错了什么

paintComponent
起作用,我知道这一点,因为我根据该代码显示了一个正方形。
我使用的是book Head First Java。

而不是使用相对路径:
“test.png”
尝试绝对路径
“c:/path/to/test.png”
尝试将图像的路径设置为

File file =new File("path");
Image picture =new ImageIcon(file);
也可以使用.getabslotePath
因为在您的情况下,图像位置应该在同一个文件夹中

管理图像的最佳方法是在您的项目中创建一个文件夹:“src/resources”,并在使用以下代码加载图像后将图像复制到该文件夹中:

InputStream stream = getClass().getClassLoader().getResource("myImage.png");
ImageIcon icon= new ImageIcon(ImageIO.read(stream));

这应该可以在IDE中使用,并且在应用程序以jar文件分发时也可以使用;)

您确定该图像已创建吗?如果没有,请尝试将路径更改为
/test.jpg
1。切勿从绘画方法中上载图像。上载一次,将其保存到变量,然后在paintComponent中使用该变量进行绘制。2.只有在将所有组件添加到JFrame后,才调用
setVisible(true)
。3.使用资源而不是文件上载图像。它与完整路径(“c:/path/to/test.png”)一起工作。但当我改变路径时,如何处理这个问题呢?有可能用短路径显示文件吗?如果文件名是固定的,可以考虑创建一个文件夹,例如图像(包含图像文件),然后将图像文件夹添加到类路径中;因此,代码
Image picture=newimageicon(“test.jpg”).getImage()
;现在将变成
Image picture=new ImageIcon(getClass().getResource(“/test.jpg”))。getImage()
No。应该使用相对路径和资源,否则程序将在一台计算机上工作,并且只能在一台计算机上工作。