【问题标题】:I can't display image from file (paintComponent) [duplicate]我无法显示文件中的图像(paintComponent)[重复]
【发布时间】:2017-12-29 11:54:44
【问题描述】:

我在显示文件中的图像时遇到问题:

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 的文件夹中有文件test。 我不知道我做错了什么。

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

【问题讨论】:

  • 您确定 Image 已创建吗?如果没有,请尝试将路径更改为/test.jpg
  • 1.切勿从绘画方法中上传您的图像。上传一次,将其保存到一个变量中,然后在paintComponent 中使用该变量进行绘制。 2. 仅在将所有组件添加到 JFrame 之后 调用setVisible(true)。 3. 使用资源而不是文件来上传图片。

标签: java paintcomponent


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 它适用于完整路径(“c:/path/to/test.png”)。但是当我改变路径时如何处理这个问题?有可能显示短路径的文件吗?
    • 如果文件名是固定的,你可以考虑创建一个文件夹,例如图像(包含图像文件),然后将图像文件夹添加到类路径;所以,代码Image picture = new ImageIcon("test.jpg").getImage();现在将变为Image picture = new ImageIcon(getClass().getResource("/test.jpg")).getImage()
    • 没有。应该使用相对路径和资源,否则程序只能在一台计算机上运行。
    【解决方案3】:

    尽量把图片的路径写成这样

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

    你也可以使用 .getabslotePath 因为在你的情况下,图像位置应该在同一个文件夹中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-22
      • 2017-03-29
      • 2017-05-13
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      • 2017-12-24
      相关资源
      最近更新 更多