【问题标题】:My java graphics.drawImage() doesn't show the image passed to it我的 java graphics.drawImage() 没有显示传递给它的图像
【发布时间】:2014-02-01 02:30:22
【问题描述】:

我正在用 java 创建一个简单的应用程序,它在 JFrame 上显示 JPEG 图像。 我创建了一个类 MyPanel,它扩展了 JPanel 并覆盖了 paintComponent() 方法:

import javax.swing.*;
import java.awt.*;

public class MyPanel extends JPanel {

    public void paintComponent(Graphics graphics)
    {
        Image image = new ImageIcon("ax.jpeg").getImage();

        graphics.drawImage(image, 1, 1, this);
    }
}

然后我将新创建的面板添加到我的主应用程序类的 JFrame 中:

import javax.swing.*;

public class MyGraphicalApp {

    public JFrame jFrame = new JFrame();
    public MyPanel myPanel = new MyPanel();

    public static void main(String[] args) {
        MyGraphicalApp myGraphicalApp = new MyGraphicalApp();
        myGraphicalApp.go();
    }

    public void go()
    {
        jFrame.getContentPane().add(myPanel);

        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setSize(300,300);
        jFrame.setVisible(true);
    }
}

问题是它根本不显示图像。我的图像驻留在我的源文件中:

src
   ------- ax.jpeg
   |
   ------- MyGraphicalApp.java
   |
   ------- MyPanel.java

感谢您的帮助。

【问题讨论】:

  • 您确定要在每次渲染应用程序时重新加载图像吗?

标签: java swing jframe jpanel awt


【解决方案1】:

确保将图像文件所在的目录添加到类路径中。然后像这样在你的类构造函数中加载图像:

protected BufferedImage image;

public MyPanel() throws IOException {
    URL imageURL = getClass().getResource("/ax.jpeg");
    if (imageURL == null) {
        throw new FileNotFoundException();
    }
    this.image = ImageIO.read(imageURL);
}

【讨论】:

  • +1 这样可以防止在调整组件大小时重新加载图像。还可以考虑在 paintComponent() 实施开始时提及缺少的 super.paintComponent(g);
  • @dic19 并非严格要求您致电super.paintComponent(g)。不过,API 文档列出了一些合同,以防您选择不这样做。
猜你喜欢
  • 1970-01-01
  • 2019-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
  • 1970-01-01
  • 1970-01-01
  • 2013-01-28
相关资源
最近更新 更多