Printwriter multiple lines with StringBuilder to CSV-file

I have 100 particles that all move with the help of Timer and ActionListener. I’m tracking the movement of my particles by saving the coordinates x,y in a StringBuilder. When the process is done I’m trying to print the results into a CSV-file, with an output that looks like this;

time1, x1, y1, x2, y2, ... , xn, yn
time2, x1, y1, x2, y2, ... , xn, yn
, At the moment the timer stops after the particles have moved 100 times, I use a counter in my ActionListener to get this done. The problem is, my output in my CSV-file looks all messed up with more than 600 rows, it should only have 100 rows.

I’ve tried using different “newline”-commands like n, rn, %n, but none of them gives me 100 lines.

The reason I want to use a StringBuilderand not just use +is because I want the code to work for as many particles as possible. If you have any other suggestions, I would gladly take them.

Below are the parts of the code I think you might need to understand the problem. If anyone wants/needs more, I can post all the code.


public class Controller extends JPanel implements ChangeListener, ActionListener{

    Model model;
    View view;
    private Timer timer;
    private int delta = 100;
    private StringBuilder csv = new StringBuilder();
    private int counter = 0;
    private int time = 2000;

    public Controller(Model m, View v) {
        model = m;
        view = v;
        timer = new Timer(delta, this);

    public void actionPerformed(ActionEvent arg0) {


        time += delta * 0.001;

        if (counter>100) {
            PrintWriter pw;
            try {
                pw = new PrintWriter("data.csv");
            } catch (FileNotFoundException e) {


public class Model {

    public int numberofparticles;
    public ArrayList<Particle> particlelist;
    public StringBuilder position = new StringBuilder();

    Model() {
        particlelist = new ArrayList<Particle>();
        numberofparticles = 100;
        for (int i = 0; i < numberofparticles; i++) {
            particlelist.add(new Particle());

    public void updatePos() {
        for (int i = 0; i < numberofparticles; i++) {
        particlelist.get(i).x += 2*Math.cos(Math.random()*2*Math.PI);
        particlelist.get(i).y += 2*Math.sin(Math.random()*2*Math.PI);

    public StringBuilder getPos() {
        for (int i=0; i < numberofparticles; i++) {
        return position;

Particle is a nested class in Model. All it does is give the particle a starting coordinate x,y