How can I keep the lines that have been drawn previously after calling repaint()

this is my paintComponent

  public void paintComponent( Graphics g )
  {
      graphics2D = (Graphics2D)g;
      graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      graphics2D.setPaint(Color.white);
      graphics2D.fillRect(0, 0, getSize().width, getSize().height);
      graphics2D.setColor(Color.black);
  }

I've another method

  public void show_line(line a)
  {
      graphics2D=(Graphics2D)this.getGraphics();
      for(int i=1;i<a.getLine_segs().size();i++)
      {
          Point p1=a.getLine_segs().get(i-1);
          Point p2=a.getLine_segs().get(i);
          System.out.println(p1);
          graphics2D.drawLine(p1.x, p1.y, p2.x, p2.y);
      }
  }

When I'm calling show_line lines are drawn..
But after calling repaint() from other methods then the drawn lines are gone. So how to keep them?

Recommended Answers

All 4 Replies

You will have to draw all the lines every time. Save the coordinates for the lines in a list and go through the list and draw the lines every time in the paint method. You should call the show_line() method from the paintComponent() method passing it the Graphics object.

Or create an image, draw the lines as desired on the image and then draw the image in the paint method.

No. I can't draw image because the lines must be added such that it can be removable later if needed.
Is the there any way such that the lines can be added as Component as we do in JComponent?

because if the list size increases, then it will take time to draw this lines.

Those are the choices I know of:
save the lines in a list - this would allow you to remove lines
draw the lines on an image - this would not allow lines to be removed (they could be drawn over with background color)

Okay. I think i have left with no other option except to make a list and use that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.