Java2D:创建形状固定装置

Java2D:创建形状固定装置,java,swing,shape,java-2d,Java,Swing,Shape,Java 2d,我想知道是否有一种在Java2D中创建形状固定装置的方法 更具体地说,我试图能够在不同的位置用不同的颜色绘制预定义的形状 我知道你可以使用fill(shape)方法来绘制形状。 但是,这似乎需要在我要绘制的坐标处创建一个新形状 有没有办法每次都重复使用相同的形状?或者我必须为每个位置创建一个新形状。您可以通过转换图形对象的变换矩阵来实现这一点。 假设您有一个名为Shape的形状,其坐标相对于形状的中心。您还有一个名为g2的Graphics2D实例 现在,您的代码可以如下所示: // Set th

我想知道是否有一种在Java2D中创建形状固定装置的方法

更具体地说,我试图能够在不同的位置用不同的颜色绘制预定义的形状

我知道你可以使用
fill(shape)
方法来绘制形状。 但是,这似乎需要在我要绘制的坐标处创建一个新形状


有没有办法每次都重复使用相同的形状?或者我必须为每个位置创建一个新形状。

您可以通过转换图形对象的变换矩阵来实现这一点。
假设您有一个名为
Shape
形状
,其坐标相对于
形状的中心。您还有一个名为
g2
Graphics2D
实例
现在,您的代码可以如下所示:

// Set the color of the Shape.
g2.setColor(Color.BLACK);
// Backup the transformation matrix so we can restore it later.
AffineTransform backupTransform = new AffineTransform(g2.getTransform());
// Translate everything that is drawn afterwards by the given coordinates.
// (This will be the new position of the center of the Shape)
g2.translate(53, 27);
// Draw the Shape.
g2.draw(shape);
// Restore the old transform, so that things drawn after this line
// are not affected by the translation.
g2.setTransform(backupTransform);

您可以通过转换图形对象的变换矩阵来完成此操作。
假设您有一个名为
Shape
形状
,其坐标相对于
形状的中心。您还有一个名为
g2
Graphics2D
实例
现在,您的代码可以如下所示:

// Set the color of the Shape.
g2.setColor(Color.BLACK);
// Backup the transformation matrix so we can restore it later.
AffineTransform backupTransform = new AffineTransform(g2.getTransform());
// Translate everything that is drawn afterwards by the given coordinates.
// (This will be the new position of the center of the Shape)
g2.translate(53, 27);
// Draw the Shape.
g2.draw(shape);
// Restore the old transform, so that things drawn after this line
// are not affected by the translation.
g2.setTransform(backupTransform);

一个,但是你介意一些格式,这样评论就可以在不滚动的情况下阅读吗?太好了,这适合我需要做的事情。谢谢:)一起来,但是你介意一些格式,这样评论就可以在不滚动的情况下阅读吗?太好了,这对我需要做的事情很有用。谢谢:)