2

Can I capture only an element of a Swing GUI (e.g. a JPanel containing some JTextFields)?

Rendicahya
  • 4,205
  • 7
  • 36
  • 56
  • 1
    What does "capture" mean? Do you want to get the text from the text field? Or maybe make an image of the text field? Or maybe you want to know when someone enters text in the tet field? Be specific with your question if you want a specific answer. – camickr Dec 25 '10 at 16:20
  • What I mean is to get an image of a user interface, in this case, the JPanel, with all contained elements. – Rendicahya Dec 25 '10 at 16:28

2 Answers2

3

The following method should capture a Swing GUI element:

public void captureComponent(JComponent component, File imageFile) throws IOException {
    BufferedImage bufImage = new BufferedImage(component.getSize().width, component.getSize().height, BufferedImage.TYPE_INT_RGB);  
    component.paint(bufImage.createGraphics());   
    imageFile.createNewFile();  
    ImageIO.write(bufImage, "jpeg", imageFile);
}
  • 1
    Yes, that is the "basic" code, but it doesn't work in all cases, which is why I try to provide a more general solution to handle the exceptions. See this question: http://stackoverflow.com/questions/4515902/how-to-remove-the-title-bar-from-a-jframe-screenshot – camickr Dec 25 '10 at 17:12
2

Screen Image will do what you want.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • +1 for the nice wrapper class, and explanation about why you can't use the above technique for AWT classes. – I82Much Dec 26 '10 at 02:56