Reputation: 13
I have a simple program with JFrame and Jpanel on it and I want to draw a line on the JPanel and save the result of the drawing to an image. But it completely does not work.
Where was I wrong?
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class source {
public static void main(String[] args) {
JFrame window = new JFrame("TEST");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setVisible(true);
mainPanel.setSize(800, 600);
mainPanel.setPreferredSize(new Dimension(300,300));
window.setContentPane(mainPanel);
window.setSize(800, 600);
window.pack();
window.setVisible(true);
Graphics g = mainPanel.getGraphics();
g.setColor(Color.BLACK);
g.drawLine(0, 0, 50, 50);
BufferedImage image = (BufferedImage)mainPanel.createImage(300, 300);
try {
System.out.println("Saved");
ImageIO.write(image, "PNG", new File("filename1.png"));
} catch (IOException ex) {
Logger.getLogger(source.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Not saved");
}
}
}
Upvotes: 0
Views: 386
Reputation: 324118
Don't use getGraphics(). That is not how you do custom painting.
Instead you need to override the paintComponent()
method of the JPanel and do your custom painting in that method. Read the section from the Swing tutorial on Custom Painting for more information and working examples.
BufferedImage image = (BufferedImage)mainPanel.createImage(300, 300);
All that does is create an empty BufferedImage.
You need to paint something on the BufferedImage by using its Graphics object. The basic code is something like:
BufferedImage image = new BufferedImage(theWidth, theHheight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
someComponent.print( g2d );
g2d.dispose();
However the above logic will only work when done on a visible GUI. This means you would need to create your frame and add the panel to the frame. Then you would create a "Save Image" button to add to the frame. Then you add an ActionListener to the button. In the listener code you create the BufferedImage and save the image to a file.
Or if you just want to create an image and save it to a file then you just paint directly to the BufferedImage:
BufferedImage image = new BufferedImage(theWidth, theHheight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setColor( Color.WHITE );
g2d.fillRect(0, 0, theWidth, theHeight);
g2d.setColor( Color.Black );
g2d.drawLine(...);
g2d.dispose();
Upvotes: 1