如何获取paint/paintComponent生成的图像?

use*_*298 5 java swing paint jcomponent

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

我有一个JComponent,我用它作为'工作区',我已经覆盖了paintComponent方法到我自己的方法.问题是我的工作区JComponent也有子项,它们有自己的paintComponent方法.

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

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

我怎么做?

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

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;
}
Run Code Online (Sandbox Code Playgroud)

欢迎任何想法或意见!:)

Mar*_*ijn 3

如果您太早调用 getImage,您的组件将尚未显示,并且宽度和高度仍为 0。您是否确定在足够晚的时间调用它?尝试将组件的大小打印到标准输出并查看其尺寸。