I am trying to create a BufferedImage from a JPanel, without using a JFrame. Yesterday, I was finally able to get the image to appear with help from this community (see below), but now I'm having some layout trouble. All of the components on the BufferedImage begin drawing at 0,0, instead of following the layout manager. Does anyone know of a solution for this problem?
Yesterday's question: Can I create a BufferedImage from a JPanel without rendering in a JFrame?
In the code below, the two labels will overwrite each other in the top left corner of the image.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class RenderTest {
RenderTest() {
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
panel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
Dimension dim = new Dimension(150,50);
panel.setSize(dim);
panel.setMinimumSize(dim);
panel.setMaximumSize(dim);
panel.setPreferredSize(dim);
JLabel label = new JLabel("hello");
JLabel label2 = new JLabel(" world");
label.setSize(label.getPreferredSize());
label2.setSize(label2.getPreferredSize());
panel.add(label);
panel.add(label2);
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();
}
}