开发者

Image Lost on Minimizing Window

I have added an image to a Canvas and then display that canvas on Panel. But when I minimize and then maximize the Window, the image disappears from the Panel. How can I solve this? Following is the code:

public class CloseCanvas extends Canvas{

    private static final long serialVersionUID = 2L;

    @Override
    public void paint(Graphics g) {
        setSize(new Dimension(30,22));
        BufferedImage image = null;

        try {
            image = ImageIO.read(new File("res/close.png"));
        } catch 开发者_如何转开发(IOException ex) {
            ex.printStackTrace();
        }

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

    }
}


This incorporates the advice of Fredrik and mKorbel, plus a few other tips unrelated to the immediate problem.

public class CloseCanvas extends Canvas{

    private static final long serialVersionUID = 2L;
    BufferedImage image = null;

    CloseCanvas() {
        try {
            image = ImageIO.read(new File("res/close.png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        setPreferredSize(new Dimension(30,22));
    }


    @Override
    public void paint(Graphics g) {
        if (image!=null) {
            g.drawImage(image, 0, 0, this);
        }
    }
}


I'd suggest you move out the image loading from the paint method. It seems quite static and for every repaint of the Canvas the image will be reloaded which happens many, many times and that will happen on the event dispatch thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜