1

I am trying to draw on the glass pane part of a JFrame with a marker using g.fillPolygon(xValues, yValues, numPoints) after making the background of the JFrame transparent.

I am using a method to find the location of the cursor and can get the right locations. To force the call of paintComponent(Graphics g), I am using myGlassPane.repaint() but this deletes the previous part of the segment that I drew.

I am wondering if there is a way to retain what was previously drawn through the paintComponent(Graphics g) method.

Mandar Pandit
  • 2,171
  • 5
  • 36
  • 58
Bryan Ho
  • 13
  • 1
  • 5

1 Answers1

1

I am wondering if there is a way to retain what was previously drawn through the paintComponent(Graphics g) method.

Yes, add whatever you drew before either to a BufferedImage or a List which can allow you to create it...

For example

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I question from my side, would it be ok to simply not call the super.paint(g) thus retaining same Graphics, and call it when you want to flush it? – Arvy Aug 20 '14 at 06:41
  • @Arvy No. See [Painting in AWT and Swing](http://www.oracle.com/technetwork/java/painting-140037.html) for details how painting works in Swing. At any time, a repaint could be triggered, many of which are outside of your control, which could force the component to redraw itself. Painting is destructive process, not an accumulative one. The only chance you "might" have of doing something like this, is drawing to `BufferedImage` and painting that in your `paintComponent` method, but this brings other issues along with it... – MadProgrammer Aug 20 '14 at 06:46
  • Consider following code: http://txs.io/Idqb . It works. But is it ethical to do so? If not, then why? – Arvy Aug 20 '14 at 07:16
  • 1
    Remember, a `Graphics` context is a shared resource, this means that anything that was painted before your component will still on the `Graphics` context. You should avoid overriding `paint` and use `paintComponent` instead, as you've broken the paint chain which can lead to any number of painting issues, which you will bang you head against a brick wall trying to fix... – MadProgrammer Aug 20 '14 at 07:19
  • Ty for enlightening me. – Arvy Aug 20 '14 at 07:23