AuroMetal pointed me to this tutorial and I extracted, that JPanel
has no idea, what it has already drawn, so you have to maintain an ArrayList
of everything to be drawn and cycle it through on every repaint()
:
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Canvas extends JPanel implements LinePrinter {
private static final long serialVersionUID = 1L;
private ArrayList<Line> lines = new ArrayList<Line>();
public Canvas(String title) {
// Just generating a JFrame to display this JPanel
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 425);
frame.setVisible(true);
frame.add(this);
}
@Override
public void addLine(Line line) {
lines.add(line);
this.repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Line line : lines) {
g.drawLine(line.A.x, line.A.y, line.B.x, line.B.y);
}
}
}
where my custom Line
class is
public class Line {
public final Point A, B;
public Line(Point A, Point B) {
this.A = A;
this.B = B;
}
}
and my custom Point
class is
public class Point {
public final int x;
public final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}