When creating a BufferedImage from a JPanel (w/o a JFrame), can I also use a layout manager?

僤鯓⒐⒋嵵緔 提交于 2019-12-02 00:49:57
Andrew Thompson

More tips from the queen. 'Call addNotify()'.

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class RenderTest {

    RenderTest() {
        JPanel panel = new JPanel(new GridLayout(0,1,10,10));
        panel.setBackground(Color.RED);
        panel.setBorder(new EmptyBorder(5,25,5,25));

        JLabel label = new JLabel("hello");
        panel.add(label);
        JLabel label2 = new JLabel("goodbye");
        panel.add(label2);

        panel.addNotify();
        panel.setSize(panel.getPreferredSize());
        panel.validate();

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

BTW - I would not recommend setting the sizes to arbitrary dimensions and then attempt to combine that with layouts. Just thought I'd mention that since I'm getting the impression that is what you want. This is a situation where we might position everything exactly so that is one way to go, but choose one approach or the other.

avajevoli
JLabel label = new JLabel("hello");
panel.add(label);
JLabel label2 = new JLabel("goodbye");
panel.add(label2);

Could this be a system requined process?

I'm not sure, but the tree looks like it might.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!