Search code examples
javaarraylistjtextarea

Filling JTextArea with Objects out of an Array


I've got a problem with this method. I want to fill a TextArea with objects from an ArrayList which i can make in a GUI. The objects are created without a problem but when i create another object, the old ArrayList is still appearing in the TextArea, but actually i only want to let show the full ArrayList again without duplications taking place inside of it.

//The code that is presenting the text in the TextArea

public void addTextBlock(double length, double width, double height) {

    shapecontrol.makeBlock(length, width, height);
    for(int i = 0; i < shapecontrol.getShapeCollection().giveCollection().size(); i++)
     {
        InfoShapeTextArea.append(shapecontrol.getShapeCollection().giveShape(i).toString() + "\n");

     } 
}

The .makeBlock method:

public void makeBlock(double length, double width, double height)
{

    Shape shape= new Block( length,  width, height);
    shapecollection.addShape(shape);

}

The .getShapeCollection() method:

public ShapeCollection getShapeCollection() {
    return shapecollection;
}

The .giveCollection() method:

public ArrayList<Shape> giveCollection(){
   return shapecollection;
}

the .giveShape() method:

public Shape giveShape(int index){


  return shapecollection.get(index);     

}

Solution

  • You either need to clear the InfoshapeTextArea between calls to addTextBlock:

    public void addTextBlock(double length, double width, double height) {
        shapecontrol.makeBlock(length, width, height);
            InfoShapeTextArea.clear(); // or setText("") or whatever will clear the text area
            for(int i = 0; i < shapecontrol.getShapeCollection().giveCollection().size(); i++)
            {
                InfoShapeTextArea.append(shapecontrol.getShapeCollection().giveShape(i).toString() + "\n");
            }
    }
    

    or just append the latest text block, not the entire contents of the ArrayList, unless you have a compelling reason to keep rewriting the same information:

    public void addTextBlock(double length, double width, double height) {
        shapecontrol.makeBlock(length, width, height);
        int size = shapecontrol.getShapeCollection().giveCollection().size();
        InfoShapeTextArea.append(shapecontrol.getShapeCollection().giveShape(size-1).toString() + "\n");
    }
    

    You could make things even simpler by just returning the Shape object from your call to makeBlock:

    public Shape makeBlock(double length, double width, double height)
    {
        Shape shape= new Block( length,  width, height);
        shapecollection.addShape(shape);
        return shape;
    }
    

    Then:

    public void addTextBlock(double length, double width, double height) {
        Shape shape = shapecontrol.makeBlock(length, width, height);
        InfoShapeTextArea.append(shape.toString() + "\n");
    }