Reputation: 641
I'm trying to write a java swing program that draws lines (Coordinates are stored in a Points ArrayList). It does that, but it refreshes/erases the previous line. I'm wondering what I have to do to keep all lines.
Thanks for looking.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
public class Draw extends JPanel {
private ArrayList<Point> points;
public Draw() {
points = new ArrayList<Point>();
MouseAdapter adapter = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
points.clear();
points.add(e.getPoint());
repaint();
}
public void mouseReleased(MouseEvent e){
points.add(e.getPoint());
repaint();
}
public void mouseDragged(MouseEvent e){
points.add(e.getPoint());
repaint();
}
};
this.addMouseListener(adapter);
this.addMouseMotionListener(adapter);
}
public void paintComponent(Graphics g){
if (points.size() > 1) {
Point p1 = points.get(0);
for (int i = 1; i < points.size(); i++){
Point p2 = points.get(i);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
Draw draw = new Draw();
frame.setContentPane(draw);
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Upvotes: 0
Views: 133
Reputation: 324118
It does that, but it refreshes/erases the previous line.
points.clear();
I would think the clear() method is removing all your previous points.
If you keep storing individual points the size of the List can get very large. Instead you may want to consider drawing directly to a BufferedImage. This way you don't need to store each point as a mouseDragged event is generated.
Upvotes: 2