Sign in to follow this  
ZeHa

[java] Bitmap Dump of GUI Elements

Recommended Posts

Hello! It's not only game-related, but I've got a little question about Java. Is there any (easy) possibility to convert, say, Swing Components of your GUI to a bitmap file? Let's assume I've got a JPanel or some other container component on my window, and my goal is to convert the whole panel with all its components to a bitmap - e.g. a "toBitmap()" method. I found methods like "print()" and so on but I'm not quite sure if they are what I'm looking for / I couldn't figure out what to do with them. Thanks in advance! Nice greetings ZeHa

Share this post


Link to post
Share on other sites
Well, I just found the solution :)

For those who are also interested, I'll share the code:


private boolean SavePanelBitmap(JPanel jp, String filename)
{
int width = jp.getWidth();
int height = jp.getHeight();

BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();

jp.paint(g2d);

try
{
File file = new File(filename);
ImageIO.write(bi, "bmp", file);
}
catch (Exception e)
{
return false;
}

return true;
}

Share this post


Link to post
Share on other sites
Quote:
Original post by ZeHa
Well, I just found the solution :)

For those who are also interested, I'll share the code:


private boolean SavePanelBitmap(JPanel jp, String filename)
{
int width = jp.getWidth();
int height = jp.getHeight();

BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();

jp.paint(g2d);

try
{
File file = new File(filename);
ImageIO.write(bi, "bmp", file);
}
catch (Exception e)
{
return false;
}

return true;
}

are you sure that works? I only get a blank image that is the same color as the component background color.

Share this post


Link to post
Share on other sites
Well I found out that the Panel must be VISIBLE in order to save the bitmap!

It should work if you put a jp.setVisible(true) at the beginning of the method and a jp.setVisible(false) at the end! Hope that works...

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