我遇到了这个方法的问题。我想用一个可以在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);
}
答案 0 :(得分: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
调用回复到<{1}}即可让事情更简单:
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");
}