最小化窗口时图像丢失

发布于 2024-12-06 11:14:11 字数 525 浏览 1 评论 0原文

我已将图像添加到画布,然后在面板上显示该画布。但是,当我最小化然后最大化窗口时,图像从面板中消失。我该如何解决这个问题?以下是代码:

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);

    }
}

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);

    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

硪扪都還晓 2024-12-13 11:14:11

这结合了 Fredrik 和 mKorbel 的建议,以及一些与当前问题无关的其他提示。

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);
        }
    }
}

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);
        }
    }
}
千鲤 2024-12-13 11:14:11

我建议您从绘制方法中移出图像加载。它看起来相当静态,对于画布的每次重新绘制,图像都会重新加载,这种情况会发生很多很多次,并且会在事件分派线程上发生。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文