我有一个保存所有形状的数组列表。
ArrayList<Shape> shapes = new ArrayList<Shape>();
ArrayList 的类型为 Shape
,因此有椭圆、矩形、直线、点。但现在我想绘制一个三角形并将其保存到同一个 ArrayList 中。
可以这样做吗?我的意思是,除了 Ellipse2D
、Rectangle2D
等之外,我可以向该 Shape
添加其他形状吗?
已编辑
这就是我用来绘制矩形的方法,例如:
private Rectangle2D.Float drawRectangle(int x1, int y1, int x2, int y2) {
// Get the top left hand corner for the shape
// Math.min returns the points closest to 0
int x = Math.min(x1, x2);
int y = Math.min(y1, y2);
// Gets the difference between the coordinates and
int width = Math.abs(x1 - x2);
int height = Math.abs(y1 - y2);
return new Rectangle2D.Float(x, y, width, height);
}
那么为了绘制我的三角形,我需要这个?
公共(public)类三角形实现 Shape{
那我在这里传递参数来画三角形?
最佳答案
查看Playing With Shapes一些有趣的想法。
它向您展示了如何使用 Polygon 类创建三角形:
Polygon triangle = new Polygon();
triangle.addPoint(0, 0);
triangle.addPoint(15, 30);
triangle.addPoint(30, 0);
shapes.add( triangle );
它还展示了如何使用链接中提供的实用程序类来制作更复杂的形状,例如星形和六边形。
关于java - 我可以在Java中将椭圆2D矩形2D之外的其他形状添加到 "Shape"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28906062/