I am trying to draw some lines on JPanel. My code adds each line to ArrayList, and then the for loop should go through it to draw each line. But instead, I get this odd conclusion.
This is my code:
public class DrawPanel extends JPanel {
private static final long serialVersionUID = 1697489704611349844L;
private static final int WIDTH = 600;
private static final int HEIGHT = 300;
private static final int STROKE_WIDTH = 1;
private int myX;
private int myY;
private int myXEnd;
private int myYEnd;
private List<Line2D> myLines = new ArrayList<Line2D>();
private List<MouseEvent> myPoints = new ArrayList<MouseEvent>();
public DrawPanel() {
super();
setBackground(Color.WHITE);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
addMouseListener(myMouseHandler);
addMouseMotionListener(myMouseMotionHandler);
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
}
private final MouseMotionListener myMouseMotionHandler = new MouseMotionAdapter() {
@Override
public void mouseDragged(final MouseEvent theEvent) {
myXEnd = theEvent.getX();
myYEnd = theEvent.getY();
myPoints.add(theEvent);
repaint();
}
};
private final MouseListener myMouseHandler = new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent theEvent) {
myX = theEvent.getX();
myY = theEvent.getY();
myXEnd = theEvent.getX();
myYEnd = theEvent.getY();
repaint();
}
@Override
public void mouseReleased(final MouseEvent theEvent) {
myXEnd = theEvent.getX();
myYEnd = theEvent.getY();
myPoints.add(theEvent);
repaint();
}
};
@Override
public void paintComponent(final Graphics theGraphics) {
super.paintComponent(theGraphics);
final Graphics2D g2d = (Graphics2D) theGraphics;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setPaint(new Color(51, 0, 111));
g2d.setStroke(new BasicStroke(STROKE_WIDTH));
myLines.add(new Line2D.Double(myX, myY, myXEnd, myYEnd));
for (Line2D l : myLines) {
g2d.draw(l);
}
}
}
And this is what he draws on the panel when I move the cursor in a circle. This is a bunch of lines connected at a central point. But I want him to be able to draw several separate lines. [![1]](https://fooobar.com/undefined)
And this is the type of line that I would like to draw, but a few of them, if the previous drawn lines did not disappear. Therefore, why did I use ArrayList to redraw the lines to keep them in the panel.
[![2]](https://fooobar.com/undefined)
source
share