目前,您的六边形看起来在您希望它居中的位置的上方和左侧。因此,对x[] 中的每个整数添加相同的数量,并从y[] 中的每个整数减去相同的数量。这些数组中的整数表示六边形顶点的 x 和 y 坐标。
我会尝试随机数量来缩小要加减的确切数量。例如,乍一看,您似乎需要将 100 加到 x[] 并从 y[] 中减去 20。您可以硬编码这些值:
int x[] = {375 + 100, 400 + 100, 450 + 100, 475 + 100, 450 + 100, 400 + 100};
int y[] = {150 - 20, 100 - 20, 100 - 20, 150 - 20, 200 - 20, 200 - 20};
或者你可以节省一些时间来缩小值并运行一个循环:
public void poligon(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Polygon pol;
// the x and y coordinates of the vertices of your hexagon
int x[] = {375, 400, 450, 475, 450, 400};
int y[] = {150, 100, 100, 150, 200, 200};
// how much to offset the x and y coordinates by
int xOffset = 100;
int yOffset = 20;
// offset your hexagon until you narrow down the right position
for(int i = 0; i < x.length; ++i) {
x[i] += xOffset;
y[i] -= yOffset;
}
pol = new Polygon(x, y, x.length);
g2d.setPaint(Color.red);
g2d.fill(pol);
}
注意:计算中心坐标的方法要简单得多,但使用您提供的代码,这是我能提供的唯一解决方案。