如何获得paint/paintComponent生成的图像? [英] How do I get the image paint/paintComponent generates?

查看:123
本文介绍了如何获得paint/paintComponent生成的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简短的问题.如何获取由JComponent.paint或paintComponent生成的图像?

I have a quick question. How do I get the image generated by a JComponent.paint or paintComponent?

我有一个JComponent,我将其用作工作区",并且在这里我已经将paintComponent方法覆盖为自己的方法.事实是,我的工作区JComponent也有一些子级,它们具有自己的paintComponent方法.

I have a JComponent which I use as a 'workspace' and where I have overwritten the paintComponent method to my own. The thing is that my workspace JComponent also has children which has their own paintComponent methods.

因此,当Swing渲染我的工作区组件时,它将先渲染工作区图形,然后再渲染其子级图形.

So when Swing renders my workspace component, it renders the workspace graphics and then its childrens'.

但是,我想获取工作区组件生成的图像(包括工作区图形和子级图形).

However, I want to get the image my workspace component generates (which includes the workspace graphics and the children's graphics).

我该怎么做?

我试图通过使用自己的Graphics来调用自己的paintComponent/paint-method,但是我只返回了一个黑色图像.这是我尝试过的;

I tried to call the paintComponent/paint-method myself by using my own Graphics, but i just returned a black image. Here is what i tried;

public void paintComponent(Graphics g) {

    if (bufferedImage != null) {
        g.drawImage(bufferedImage, 0, 0, this);
    }
    else {
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());
    }
}

public BufferedImage getImage() {

    BufferedImage hello = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics g = hello.getGraphics();
    paintComponent( g );

    return hello;
}

欢迎任何想法或评论! :)

Any thoughts or comments are welcome! :)

推荐答案

如果过早调用getImage,则组件尚未显示,并且宽度和高度仍为0.您确定要在足够晚的时间打电话吗?尝试将组件的尺寸打印到标准输出,然后查看其尺寸.

If you call getImage too early, your component will not have been displayed yet and will still have a 0 width and height. Have you made sure you're calling it at a sufficient late time? Try printing the component's size to stdout and see what its dimensions are.

这篇关于如何获得paint/paintComponent生成的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆