Question

import java.awt.*;
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)
    {
        SwingUtilities.invokeLater(new Runnable()
        {

            @Override
            public void run()
            {
                new Main();
            }
        });
    }
}
class MyCanvas extends JComponent
{
    Image img;
    MyCanvas()
    {
        setPreferredSize(new Dimension(200,200));
        img=Toolkit.getDefaultToolkit().createImage("1.jpg");
    }
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawImage(img,0,0,null);
    }
}

I'd like to get canvas with its own paintComponent method, but sometimes I see empty window without image. And I need to resize window for doing visible this image. What is problem? Why drawImage doesn't draw sometimes?

Was it helpful?

Solution

Change

g.drawImage(img,0,0,null);

to

g.drawImage(img,0,0,this);

and you should be good to go.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top