Reputation: 3
I am creating a program for a school project where the user can create a geometrical shape (which is supposed to look like a horse) using buttons which control the size and color of: One Ellipse, one Circle, two Rectangles and one String (as a title for the figure). To save the figure I want an ArrayList where all of these are included, so I created a class which looks like this.
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;
}
}
Now, when I create the ArrayList I write the following (in another class):
ArrayList<WiLi_Horse> horseList = new ArrayList<>();
I then want to add a 'horse' in the ArrayList, so I begin with typing:
horseList.add(new WiLi_Horse(XXX);
Where it says 'XXX' is the problem in hand. I don't know what to write from here on. Eclipse's quick-fix is to add null, null, null, null, null, but that is ofcourse not what I want.
Thank you in advance.
Upvotes: 0
Views: 2287
Reputation: 24157
May be you can try a List
of Shape
which will accept all of them:
List<Shape> shapes = new ArrayList<Shape>();
Now you can add whatever shape you want to add:
shapes.add(body);
shapes.add(leg1);
shapes.add(leg2);
etc. Here is the complete example which you can test:
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 + '\'' +
'}';
}
}
Now you can test it as:
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);
}
Upvotes: 1