I have two JPanels on a JLayeredpane. One of them displays a pdf and the overlapping one has a transparent background (I have used setOpaque(false)). Now I can add drawings to the transparent panel such that it seems I'm actually annotating the pdf. I want to have a eraser tool to erase these annotations. I tried using the following code
@Override
public void draw(Graphics2D g2) {
g2.setPaint(Color.WHITE);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
g2.setBackground(new Color(255, 255, 255, 0));
g2.setStroke(new BasicStroke(thickness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2.draw(path);
}
where path is the shape constituted from a number of lines. Now instead of drawing a transparent line over the earlier drawings a black line is being drawn. Where am I going wrong?
Note that an instance of
AlphaComposite.CLEAR
, equivalent toAlphaComposite.Clear
, is a composite mode that clears both the color and the alpha of the destination. "Neither the source nor the destination is used as input." In effect, you can't draw withCLEAR
. This example illustrates a common usage. To get the effect you want, keep a copy of the unaltered image anddraw()
an eraser-sized sub-image over the destinationBufferedImage
as the mouse moves.