我无法显示文件中的图像(paintComponent)[重复]

问题描述 投票:-2回答:3

这个问题在这里已有答案:

我有从文件显示图像的问题:

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();
    }
}

应该很简单。我在类Drawing的文件夹中进行文件测试。我不知道我做错了什么。

paintComponent工作,我知道,因为我从这段代码中显示了一个正方形。我正在使用Head First Java。

java paintcomponent
3个回答
1
投票

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

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

这应该在您的IDE中以及应用程序在jar文件中分发时可以使用;)


0
投票

而不是使用相对路径:"test.png"尝试绝对路径"c:/path/to/test.png"


0
投票

尝试将图像的路径作为这个

File file =new File("path");
Image picture =new ImageIcon(file);

您也可以使用.getabsolutePath因为在您的情况下,图像位置shuld位于同一文件夹中

© www.soinside.com 2019 - 2024. All rights reserved.