i am implementing a class with extends a JPanel, and this class is added to a JTabPane, and you can draw things on the area like a Paint program, however when drawing a new line it will join with the previous drawing points, why is that so?
and in the for loop there is a -2 on the size of the arrayList , may i know why is it needed? i have tried removing it and it causes error.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
public class STDrawingArea extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
ArrayList<Point> Points = new ArrayList<Point>();
public STDrawingArea()
{
setBorder(BorderFactory.createLineBorder(Color.black));
setBackground(Color.WHITE);
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
Points.add(e.getPoint());
System.out.println("Dragged");
repaint();
}
});
}
@Override
public Dimension getPreferredSize() {
return new Dimension(700,600);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for(int i = 0 ; i < Points.size()-2;i++)
{
Point p1 = Points.get(i);
Point p2 = Points.get(i+1);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
}
public void clearDrawings()
{
Points.clear();
repaint();
}
}
Yes there is a -2 in the list size check, but I think that you have to increment i by 2 units:
to achieve the results you want.
Try this:
EDIT:
Looking at you picture not seems that lines are connected. I see white spaces between your lines.
Probably mouseDragged isn’t the right method to use. It throws a lot of MouseEvent events, making your code drawing a lot of disconnected lines, one close to the others.
Try doing the same thing using MousePressed or MouseClicked method. I guess you will see that your now code is correct.
a tip:
in Java conventions, field and variables should start with a low-case first letter, so change your Points declaration this way: