Sign in to follow this  
Lucidquiet

[java] JFrame to image file. [Solved]

Recommended Posts

I'm trying to output an Image file of a frame, that is menu bar, and border, etc. I'm not seeing in the javadoc where the functionality is located. Could someone please post a code snippet? Thanks, L- [Edited by - Lucidquiet on October 6, 2006 9:03:38 PM]

Share this post


Link to post
Share on other sites
I never did it before, but I would try the following... Create an image (BufferedImage) using the Graphics object retrieved through the JFrame, and use it to paint() the component again (or something similar). Then call ImageIO to write the image on a file. I don't know if you can do such a thing (i.e, paint a component on an image), but I guess the solution is something close to that.

Share this post


Link to post
Share on other sites
Here is the solution I found -- uses a Robot. The Graphics, and BufferedImage route doesn't work because java is using a peer to render the frame, titlebar, and border.

L-



import javax.swing.JFrame;
import javax.swing.SwingUtilities;

import java.awt.image.BufferedImage;

import java.awt.Rectangle;
import java.awt.AWTException;
import java.awt.Point;
import java.awt.Window;

import java.awt.Component;
import java.awt.Robot;

import javax.imageio.ImageIO;

import java.io.File;
import java.io.IOException;


public class OutputJFrame extends JFrame
{
public static void main(String[] args)
{
new OutputJFrame().begin();
}

public OutputJFrame()
{
super("Output JFrame v0.0.02");

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 400);
this.setVisible(true);
}

public void begin()
{
BufferedImage image = this.getCoponentImage(this);

try
{
ImageIO.write(image, "jpg", new File("OutputJFrame.jpg"));
}
catch(IOException io)
{
io.printStackTrace();
}
}

public BufferedImage getCoponentImage(Component comp)
{
int x, y;

int width = comp.getWidth();
int height = comp.getHeight();

BufferedImage bImage = null;

//these conditionals are necessary, but I don't know why
if (comp instanceof Window)
{
x = comp.getX();
y = comp.getY();
}
else
{
Point p = comp.getLocationOnScreen();
x = p.x;
y = p.y;
}

Rectangle rec = new Rectangle(x, y, width, height);

try
{
Robot robo = new Robot();
//you need to give generous amount of delay
robo.delay(1000);
bImage = robo.createScreenCapture(rec);
}
catch(AWTException awte)
{
awte.printStackTrace();
}

return bImage;
}
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this