I'm a new poster to stackoverflow, but I've always read the posts for inspiration and I am happy to be a part of the community.
I am drawing an image to a JPanel and then I wish to save that image to a file. The painting on the JPanel goes fine, but when I look at the image it is either all white or all black. I don't know why the image is not saving the way it looks on the JPanel. I guess it is possible I am not correctly referencing the Panel when drawing the image to the buffer and saving it? Its almost like the bufferedImage is blank. I don't have a lot of experience with awt so I have a feeling I'm making a really stupid mistake.
I only overwrite the paintComponent() method once, and in it I do my drawing(which shows up flawlessly on the JPanel) and then at the bottom of it I call the saveImage() method which is supposed to save the image to a file. But as I metioned before, its always a blank image. I use the repaint() method in the constructor.
I won't bog this post down with the entire code. Its a very simple code and the relevant pieces are below.
class drawingBarcode extends JPanel
public drawingBarcode(){
repaint();
try{
Thread.sleep(999);
}catch(InterruptedException e){
e.printStackTrace();
}
public void saveImage() {
BufferedImage bi = new BufferedImage(350, 150, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();//creates and returns a graphics 2d for drawing into buffer
// g2.setColor(color1);
super.paintComponent(g2);
g2.dispose();
try
{
ImageIO.write(bi, "jpg", new File("test.jpg\\"));
}
catch(IOException ioe)
{
System.out.println("Something went wrong");
ioe.printStackTrace();
}
public void paintComponent(Graphics g){
Graphics2D g2D = (Graphics2D) g;
super.paintComponent(g2D);
setStrokeWithPen1(g2D);
drawAsterix(g2D);//draw asterix(start digit) always
/* some drawing takes place here using g2D. */
g2D.dispose();
saveImage();
}
}
Any help that can be offered or advice would be more than greatly appreciated!