I am working on a white board project and I encountered a problem when implementing the Save function.
Here is how I implement the draw function
Graphics2D g2d = (Graphics2D) frm.getGraphics();
g2d.setColor(Current_Color);
Line2D p2d = new Line2D.Double(StartPoint.getX(),StartPoint.getY(), e.getX()
+ Xoffset, e.getY() + Yoffset);
g2d.setStroke(new BasicStroke(Integer.parseInt(choice_size.getSelectedItem())));
g2d.draw(p2d);
I am using JFileChooser for the file dialog
int returnVal = saveFileChooser.showSaveDialog(frm);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File currentDir = saveFileChooser.getCurrentDirectory();
String fileName = saveFileChooser.getSelectedFile()
.getName();
String savePath = currentDir + "\\" + fileName + ".jpg";
try {
ImageIO.write(<image>,<suffix>,<file>);
} catch (IOException e1) {
e1.printStackTrace();
}
}
There is no method like Frame.getImage() for JFrame, I am wondering how can I save what I draw on the JFrame as an image ?
You need to paint the frame’s content to a
BufferedImagefirst. Try something like…Once you have that, you can use the
ImageIO.writemethod, passing theimgto it.UPDATE
So, I did a really quick test…
I started out with this background image…
Which I loaded into my frame and laid a
JLabelontopAnd then saved to a file…
All of which worked fine.
This is the code that I used.
Without an example of the work flow, it’s going to be tough to work out where you’re going wrong.
I should note that I use
printAlloverpaintbecause I’ve had issues with doing this usingpaintrecently (throwing exceptions and the like)