ImageIcon.paintIcon不在JPanel上绘制图像

时间:2015-10-27 14:24:35

标签: java swing jpanel imageicon

我试图在.png上绘制JPanel。我使用ImageIcon构造函数导入了它,并将其绘制在我的自定义面板paintComponent中。

我的sscce

package mypackage;

import java.awt.Graphics;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyPanel extends JPanel {

    static JFrame frame;
    static MyPanel panel;
    static ImageIcon icon;

    public static void main(String[] args) {
        icon = new ImageIcon(MyPanel.class.getResource("MyImage.png"));
        frame = new JFrame();
        panel = new MyPanel();
        frame.setSize(500, 500);
        frame.add(panel);
        frame.setVisible(true);
        frame.repaint();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        icon.paintIcon(panel, g, 100, 100);
    }
}

我预计在白色背景上只有几个形状的图像会在面板上的(100, 100)处显示。而是一个空白屏幕:

Blank panel where I expected my image to be drawn

没有错误发生的事实意味着程序正在正确地找到文件。

图像在我的Eclipse项目中与类相同的包中包含:

Project setup

为什么会这样?我该如何解决?

2 个答案:

答案 0 :(得分:3)

由于代码看起来正确,我建议资源没有正确加载。

将png文件放在类路径中。例如。我会有一个目录:

~/ProjectRoot/resources/mypackage/

然后在类路径中包含资源。 In eclipse you can setup the classpath via

  

项目 - >属性 - > Java构建路径 - >添加类文件夹

BufferedImage img = 
    ImageIO.read(MyPanel.class.getResourceAsStream("MyImage.png"));

如果找不到图像,则抛出异常。您可以使用它来制作ImageIcon。

答案 1 :(得分:2)

使用ImageIcon从文件中读取图像时,无法判断读取是否成功。

这是您使用ImageIO读取图像的GUI:

Image on GUI

这是图像,在与Java源相同的目录中:

enter image description here

这是你的代码,我使用ImageIO读取来读取图像,并在paintComponent方法中绘制图像。

package com.ggl.testing;

import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class MyPanel extends JPanel {

    private static final long serialVersionUID = -9008812738915944216L;

    private static JFrame frame;
    private static MyPanel panel;
    private static Image image;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                image = getImage();
                frame = new JFrame();
                panel = new MyPanel();
                frame.setSize(500, 500);
                frame.add(panel);
                frame.setVisible(true);
            }
        });
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 100, 100, MyPanel.this);
    }

    private static Image getImage() {
        Image image = null;
        try {
            image = ImageIO.read(MyPanel.class.getResource("maze.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }
}