我可以从 JPanel 创建 BufferedImage 而不在 JFrame 中呈现吗?

2022-01-24 00:00:00 java swing jpanel jframe bufferedimage

是否可以从 JPanel 创建 BufferedImage 而无需先在 JFrame 中渲染它?我已经搜索了我能想到的所有地方,但找不到答案.有人可以帮忙吗?

Is it possible to create a BufferedImage from a JPanel without first rendering it in a JFrame? I've searched everywhere I can think of and cannot find an answer. Can anyone help?

这里是一些示例代码.如果我不取消注释 JFrame 代码,我的 BufferedImage 是空白的.

Here is some sample code. If I don't un-comment the JFrame code, my BufferedImage is blank.

    test(){
//      JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        Dimension dim = new Dimension(50,50);
        panel.setMinimumSize(dim);
        panel.setMaximumSize(dim);
        panel.setPreferredSize(dim);
        JLabel label = new JLabel("hello");
        panel.add(label);
//      frame.add(panel);
//      frame.pack();
        BufferedImage bi = getScreenShot(panel);

        //...code that saves bi to a jpg
    }

    private BufferedImage getScreenShot(JPanel panel){
        BufferedImage bi = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_ARGB);
        panel.paint(bi.getGraphics());
        return bi;
    }

推荐答案

查看这个答案到Swing:获取JFrame的图片以及为什么JTable 标题没有出现在图像中? 获取有关绘制尚未渲染的组件的提示.我希望您的问题的解决方法显示在 LabelRenderTest.java 的标签中.

See this answer to Swing: Obtain Image of JFrame as well as Why does the JTable header not appear in the image? for tips on painting components that have not yet been rendered. I expect the fix to your problem is shown in the label of LabelRenderTest.java.

JLabel textLabel = new JLabel(title);
textLabel.setSize(textLabel.getPreferredSize());

Dimension dim = new Dimension(50,50);
panel.setSize(dim);  // very important!
panel.setMinimumSize(dim);
panel.setMaximumSize(dim);
panel.setPreferredSize(dim);
// ...

或者这里是完整的源代码.标签的大小也需要设置.

Or here is the complete source. The size of the label also needs to be set.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.image.BufferedImage;

import javax.swing.*;

public class RenderTest {

    RenderTest() {
        JPanel panel = new JPanel();
        panel.setBackground(Color.RED);
        Dimension dim = new Dimension(50,50);
        panel.setSize(dim);
        panel.setMinimumSize(dim);
        panel.setMaximumSize(dim);
        panel.setPreferredSize(dim);
        JLabel label = new JLabel("hello");
        label.setSize(label.getPreferredSize());
        panel.add(label);

        BufferedImage bi = getScreenShot(panel);
        JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(bi)));
    }

    private BufferedImage getScreenShot(JPanel panel){
        BufferedImage bi = new BufferedImage(
            panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_ARGB);
        panel.paint(bi.getGraphics());
        return bi;
    }

    public static void main(String[] args) {
        new RenderTest();
    }
}

相关文章