I've been working on a simple paint program and I have recently run into a snag when redrawing shapes in my paint component.
@Override
public void paintComponent(final Graphics theGraphics) {
super.paintComponent(theGraphics);
final Graphics2D g2d = (Graphics2D) theGraphics;
if (!preDrawnShapes.isEmpty() && !preDrawnShapeThickness.isEmpty()) {
for (int i = 0; i < preDrawnShapes.size(); i++) {
g2d.setStroke(new BasicStroke(preDrawnShapeThickness.get(i)));
g2d.draw(preDrawnShapes.get(i));
}
}
g2d.setStroke(new BasicStroke(currentThickness));
if (myShape != null) {
g2d.draw(myShape);
preDrawnShapeThickness.add(currentThickness);
}
}
This paintComponenent is supposed to first redraw the shapes previously drawn before before then drawing the new shape created from user input.
For some reason, the shape thickness when drawing the new shape is set to the current thickness but any shape that I drew before had a default thickness of 1.
preDrawnShapes is a Shapes ArrayList and preDrawnShapeThickiness is a Float Arraylist.
Am I missing something here?
UPDATE: I've discovered that PreDrawnShapeThickness stores only Floats of zero. I am unsure why.
There are two common ways to do incremental painting:
Keep a List of Objects that you want to paint. Then the paintComponent() method iterates through the List and paints each object. So in your case the custom object would contain the Shape you want to paint and an int value for the thickness of the shape.
Just paint each Object directly to a BufferedImage. Then you can just use a JLabel to display the BufferedImage as an Icon, or do custom painting to paint the BufferedImage.
Check out Custom Painting Approaches for examples of both approaches.