制作包含对象的ArrayList(椭圆,矩形等)

时间:2015-05-09 11:57:35

标签: java arraylist javafx geometry ellipse

我正在为学校项目创建一个程序,用户可以使用按钮来创建几何形状(看起来像马),控制尺寸和颜色:一个椭圆,一个圆,两个矩形和一个字符串(作为图的标题)。为了保存图形,我想要一个包含所有这些的ArrayList,所以我创建了一个看起来像这样的类。

import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Rectangle;

public class WiLi_Horse{

    Ellipse body;
    Rectangle leg1;
    Rectangle leg2;
    Circle head;
    String name;

    public WiLi_Horse(Ellipse bdy, 
            Rectangle lg1, Rectangle lg2, 
            Circle hd, String nme) {

        body = bdy;
        leg1 = lg1;
        leg2 = lg2;
        head = hd;
        name = nme;
    }
}

现在,当我创建ArrayList时,我编写了以下内容(在另一个类中):

ArrayList<WiLi_Horse> horseList = new ArrayList<>();

然后我想添加一匹马&#39;在ArrayList中,我首先输入:

horseList.add(new WiLi_Horse(XXX);

它所说的&#39; XXX&#39;是问题在手。我不知道从这里写什么。 Eclipse的快速修复是添加null,null,null,null,null,但这不是我想要的。

提前谢谢。

1 个答案:

答案 0 :(得分:1)

您可以试用List Shape来接受所有这些内容:

List<Shape> shapes = new ArrayList<Shape>();

现在您可以添加要添加的任何形状:

shapes.add(body);
shapes.add(leg1);
shapes.add(leg2); 

等。以下是您可以测试的完整示例:

public class WiLi_Horse {
    Ellipse body;
    Rectangle leg1;
    Rectangle leg2;
    Circle head;
    String name;

    public WiLi_Horse(Ellipse body, Rectangle leg1, Rectangle leg2, Circle head, String name) {
        this.body = body;
        this.leg1 = leg1;
        this.leg2 = leg2;
        this.head = head;
        this.name = name;
    }
    public List<Shape> getHorse()
    {
        List<Shape> shapes = new ArrayList<Shape>();
        shapes.add(body);
        shapes.add(leg1);
        shapes.add(leg2);
        shapes.add(head);
        return shapes;
    }
    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "WiLi_Horse{" +
                "body=" + body +
                ", leg1=" + leg1 +
                ", leg2=" + leg2 +
                ", head=" + head +
                ", name='" + name + '\'' +
                '}';
    }
}

现在您可以将其测试为:

public static void main(String[] args) {
        Ellipse ellipse = new Ellipse(10,20);
        Rectangle rect1 = new Rectangle(40,20);
        Rectangle rect2 = new Rectangle(40,20);
        Circle circle = new Circle(5);
        String name = "Horse";

        WiLi_Horse horse1 = new WiLi_Horse(ellipse,rect1,rect2,circle,name);
        WiLi_Horse horse2 = new WiLi_Horse(ellipse,rect1,rect2,circle,name);
        WiLi_Horse horse3 = new WiLi_Horse(ellipse,rect1,rect2,circle,name);
        WiLi_Horse horse4 = new WiLi_Horse(ellipse,rect1,rect2,circle,name);

        List<WiLi_Horse> horseList = new ArrayList<>();
        horseList.add(horse1);
        horseList.add(horse2);
        horseList.add(horse3);
        horseList.add(horse4);
        System.out.println(horseList);
    }