Convert swing component to image
package y11.m03;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
public class PrintTester {
public static void main(String[] args) throws IOException {
JPanel p = new JPanel(new GridLayout(2, 2));
p.add(new JTextField("wwww", 20));
p.add(new JLabel("dfdfdf"));
p.add(new JSpinner());
p.add(new JButton("fdfdf"));
BufferedImage image = createImage(p);
ImageIO.write(image, "png", new File("PrintTest2.png"));
}
// if component is rendered
public static BufferedImage createImage(JComponent component) {
int w = component.getWidth();
int h = component.getHeight();
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
component.paint(g);
return img;
}
// if component is not rendered
public static BufferedImage createImage(JComponent component, AffineTransform transform) throws IOException, ClassNotFoundException {
if (component == null)
return null;
JFrame f = new JFrame(); // for paint
JComponent clone = (JComponent) clone(component);
f.add(clone);
f.pack();
BufferedImage image = new BufferedImage(clone.getWidth(), clone.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
if (transform != null)
g.setTransform(transform);
clone.paint(g);
f.dispose();
return image;
}
public static <T extends Serializable> T clone(T source) throws IOException, ClassNotFoundException {
Object newObject = new Object();
ObjectOutputStream ooStr = null;
ByteArrayOutputStream baoStr = new ByteArrayOutputStream();
ooStr = new ObjectOutputStream(baoStr);
ooStr.writeObject(source);
ooStr.flush();
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(baoStr.toByteArray()));
newObject = in.readObject();
ooStr.close();
return (T) newObject;
}
}