2
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?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
eXXXXXXXXXXX2
  • 1,540
  • 1
  • 18
  • 32
  • Resize the window to issue a repaint. My wild guess would be, that the image is not yet loaded, when you draw the window initially. – ZeissS Feb 25 '12 at 15:12
  • @ZeissS i.e. `Toolkit.getDefaultToolkit().createImage("1.jpg");` this method returns even without full loading image? – eXXXXXXXXXXX2 Feb 25 '12 at 15:17

1 Answers1

4

Change

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

to

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

and you should be good to go.

stryba
  • 1,979
  • 13
  • 19
  • I don't think that this will fix his problem, but we'll have to wait to see what @eXXXXX ... has to say. – Hovercraft Full Of Eels Feb 25 '12 at 18:29
  • Yes it should, assuming his image is loadable, which it seems as it appears after resizing. Let's see what the OP says. – stryba Feb 25 '12 at 18:54
  • +1 it works, although `ImageIO` may be a better alternative. Note `JCompomponent` default [opacity](http://java.sun.com/products/jfc/tsc/articles/painting/index.html#props). – trashgod Feb 25 '12 at 19:56
  • @trashgod: you'd still want to provide a valid ImageObserver – stryba Feb 25 '12 at 23:59
  • @stryba: Isn't the [`JComponent`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html) implementation sufficient? – trashgod Feb 26 '12 at 02:49
  • @trashgod: yes as long as you actually use it which is what I propose in my answer – stryba Feb 26 '12 at 08:40