使用BufferedImage的drawImage()不会绘制

时间:2012-02-25 16:06:07

标签: java swing bufferedimage

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

public class Main
{
    JFrame jf;
    Main()
    {
        jf=new JFrame();
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.add(new MyCanvas());
        jf.pack();
        jf.setVisible(true);
    }
    public static void main(String[] args)
    {
        MyCanvas.img=Toolkit.getDefaultToolkit().createImage("1.jpg");
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new Main();
            }
        });
    }
}
class MyCanvas extends JComponent
{
    static Image img;
    BufferedImage bi;
    MyCanvas()
    {
        setPreferredSize(new Dimension(200,200));
        bi=new BufferedImage(200,200,BufferedImage.TYPE_INT_ARGB);
        Graphics g=bi.getGraphics();
        for (int i=0;i<10;i++)
            for (int j=0;j<10;j++)
                g.drawImage(img,i*20,j*20,20,20,this);
    }
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawImage(bi,0,0,this);
        //g.drawImage(img,0,0,this);
    }
}

如果我取消注释第g.drawImage(img,0,0,this);行,我会在窗口显示我的图像。但是使用这段代码我看到了空窗口。很容易理解循环中的g.drawImage(img,i*20,j*20,20,20,this);没有绘制但是什么是问题?

2 个答案:

答案 0 :(得分:3)

将我为未来读者所做的不相关的事情编辑出来,以便更容易找到答案。在java中,我总是必须使用getResource或getResourceAsStream来确保从正确的目录正确加载文件。

class MyCanvas extends JComponent
{
    public static Image loadImage(String s)
    {
        try 
        {
            return ImageIO.read(Main.class.getResource(s));
        } 
        catch (Exception ex) 
        {
            ex.printStackTrace();
            return null;
        }
    }
}

答案 1 :(得分:1)

1)将BufferedImage作为Icon添加到JLabel示例here

2)CustomCanvas中的paintComponent可能是

class MyCanvas extends JComponent {

    private static final long serialVersionUID = 1L;

    @Override
    public Dimension getMinimumSize() {
        return new Dimension(150, 150);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300, 300);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(bi,0,0,this);
    }
}