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