Skip to main content
gamedev.net
🔒 Locked

[java] Bitmap Dump of GUI Elements

Started by ZeHa 3 replies 1.2k views
Original Post
ZeHa
ZeHa
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
ZeHa
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;	}
Whackjack
Whackjack
Very cool job on this. I'll have to try and remember this solution for potential future use.
capn_midnight
capn_midnight
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.
ZeHa
ZeHa
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...

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.