0

这个方法我有问题。我想用可以在 GUI 中制作的 ArrayList 中的对象填充 TextArea。对象的创建没有问题,但是当我创建另一个对象时,旧的 ArrayList 仍然出现在 TextArea 中,但实际上我只想让完整的 ArrayList 再次显示,而不会在其中发生重复。

//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");

     } 
}

.makeBlock 方法:

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

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

}

.getShapeCollection() 方法:

public ShapeCollection getShapeCollection() {
    return shapecollection;
}

.giveCollection() 方法:

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

.giveShape() 方法:

public Shape giveShape(int index){


  return shapecollection.get(index);     

}
4

1 回答 1

0

您要么需要清除InfoshapeTextArea调用之间的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");
        }
}

或者只是附加最新的文本块,而不是 的全部内容ArrayList,除非您有令人信服的理由继续重写相同的信息:

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");
}

您可以通过将Shape对象从您的调用返回到makeBlock

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

然后:

public void addTextBlock(double length, double width, double height) {
    Shape shape = shapecontrol.makeBlock(length, width, height);
    InfoShapeTextArea.append(shape.toString() + "\n");
}
于 2013-09-18T14:35:45.880 回答