title: Drawing Geometric Shapes in Java using Swing
body: <p>I'm currently trying to build a Java Application (using Swing) to simply draw some lines on the Main-Window by clicking on the window.</p>
  <p>I currently managed to write a program that works. The following code leads to the expected result, but I don't like the way it is working.</p>
  <p>In my code the program is redrawing all the lines. Also the ones that were already existing (and shown up). I assume this is not a good practice because this leads to a lot of unnecessary work in the case the lineArray contains a lot of elements.</p>
  <p>Is there a better way to draw the lines? Can I keep the already displayed lines somehow and add only the new one?</p>
  <pre><code>public class DrawPlane extends JLabel {
  
  public ArrayList&lt;myLine&gt; lineArray;
  
  public DrawPlane() {
      this.setOpaque(false);
      
      lineArray = new ArrayList&lt;&gt;();
      
      this.addMouseListener(new MouseAdapter() {
          public void mousePressed(MouseEvent e) {
              lineArray.add(new myLine(e.getX(), e.getY(), 0, 0));
          }
          
          public void mouseReleased(MouseEvent e) {
              myLine last = lineArray.get( lineArray.size() - 1 );
              last.x2 = e.getX();
              last.y2 = e.getY();
              lineArray.set(lineArray.size() - 1, last);
              repaint();
          }
      });
  }
  
  public void DrawLines(Graphics g) {
      lineArray.forEach(lineItem -&gt; g.drawLine(lineItem.x1, lineItem.y1, lineItem.x2, lineItem.y2));
  }
  
  public void paintComponent(Graphics g) {
      super.paintComponent(g);
      DrawLines(g);
      g.setColor(Color.red);
      }
  }
  </code></pre>
  <p>Note: myLine is defined in an additional file and is a basic class with only four properties (int) x1, y1, x2 and y2.</p>
  <p>Regards Michael</p>