ComponentImageCapture.java
import java.awt.BorderLayout; import java.awt.Component; import java.awt.Image; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.InputEvent; import javax.swing.*; import javax.swing.border.TitledBorder; import javax.imageio.ImageIO; import java.io.File; class ComponentImageCapture { static final String HELP = "Type Ctrl-0 to get a screenshot of the current GUI.\n" + "The screenshot will be saved to the current " + "directory as 'screenshot.png'."; public static BufferedImage getScreenShot( Component component) { BufferedImage image = new BufferedImage( component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_RGB );
Screenshot

see also
The above code assumes that the component was implemented on the screen before rendering.
Rob Camick shows how to draw an unrealized component in the Screen Image class.
Another thread that may be relevant is Render JLabel without a 1st display , in particular, Darryl Burke's βsingle-line fixβ.
LabelRenderTest.java
Below is an updated version of the code shown on the second channel.
import java.awt.*; import java.awt.image.BufferedImage; import javax.swing.*; public class LabelRenderTest { public static void main(String[] args) { SwingUtilities.invokeLater( new Runnable() { public void run() { String title = "<html><body style='width: 200px; padding: 5px;'>" + "<h1>Do UC Me?</h1>" + "Here is a long string that will wrap. " + "The effect we want is a multi-line label."; JFrame f = new JFrame("Label Render Test"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); BufferedImage image = new BufferedImage( 400, 300, BufferedImage.TYPE_INT_RGB); Graphics2D imageGraphics = image.createGraphics(); GradientPaint gp = new GradientPaint( 20f, 20f, Color.red, 380f, 280f, Color.orange); imageGraphics.setPaint(gp); imageGraphics.fillRect(0, 0, 400, 300); JLabel textLabel = new JLabel(title); textLabel.setSize(textLabel.getPreferredSize()); Dimension d = textLabel.getPreferredSize(); BufferedImage bi = new BufferedImage( d.width, d.height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.createGraphics(); g.setColor(new Color(255, 255, 255, 128)); g.fillRoundRect( 0, 0, bi.getWidth(f), bi.getHeight(f), 15, 10); g.setColor(Color.black); textLabel.paint(g); Graphics g2 = image.getGraphics(); g2.drawImage(bi, 20, 20, f); ImageIcon ii = new ImageIcon(image); JLabel imageLabel = new JLabel(ii); f.getContentPane().add(imageLabel); f.pack(); f.setLocationByPlatform(true); f.setVisible(true); } }); } }
Screenshot

Andrew Thompson May 2 '11 at 6:15 a.m. 2011-02-02 06:15
source share