Thank you Kevin for the great code! Meanwhile I found another solution using a buffered image (as you suggested) and no timers. I post it here for the record.
You made my day!
Robert
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
class SyncPaintPanel extends JPanel {
private BufferedImage paintImage = null;
private Line2D[] linesArray;
private int lineCount, reset;
SyncPaintPanel(JFrame frame, int width, int height) {
int w, h;
Insets insets = frame.getInsets();
w = frame.getWidth() - insets.left - insets.right;
h = frame.getHeight() - insets.top - insets.bottom;
setSize(w, h);
linesArray = new Line2D[h];
for (int i = 0; i < h; i++) {
linesArray[i] = new Line2D.Double(i*w/h, i, w - i*w/h - 1, i);
}
addMouseMotionListener(new SyncMouseListener());
}
void refresh() {
if (paintImage == null) {
paintImage = (BufferedImage) createImage(getWidth(), getHeight());
}
Graphics2D g2d = paintImage.createGraphics();
reset = 1;
lineCount = 0;
while(lineCount < getHeight()) {
if(reset == 1) {
reset = 0;
lineCount = 0;
System.out.println("reset");
g2d.setColor(Color.black);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.setColor(Color.white);
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("drawing line " + lineCount);
g2d.draw(linesArray[lineCount++]);
paintImmediately(0, 0, getWidth(), getHeight());
}
g2d.dispose();
}
public void paintComponent(Graphics g) {
if (paintImage != null) {
g.drawImage(paintImage, 0, 0, this);
}
}
class SyncMouseListener extends MouseAdapter {
public void mouseMoved(MouseEvent e) {
System.out.println("mouse move");
reset = 1;
}
}
}
public class SyncPaint {
public static void main(String[] args) {
JFrame frame = new JFrame("SyncPaint");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(400, 600);
SyncPaintPanel panel = new SyncPaintPanel(frame, frame.getWidth(),
frame.getHeight());
frame.add(panel);
panel.refresh();
}
}