首页 > 解决方案 > 摆动拉绳居中

问题描述

我必须在 GUI 中水平和垂直绘制 n + 1 个圆圈。我已成功完成,如下所示。这样,将在它们之间打印一个二维字符串数组,集中。

目前情况如何

在此处输入图像描述

现在我想在点的“正方形”中绘制数字。

我想要最终的结果

在此处输入图像描述

for (int i = 0; i < width; i++) {
    for (int j = 0; j < width; j++) {
        canvas.drawCircle( (j + 1) * 125, (i + 1) * 125, 15, Color.white);
    }
}

for (int r = 0; r < size; r++) {
    for (int c = 0; c < size; c++) {
        canvas.drawString(events[r][c], (r + 1) * 150, (c + 1) * 150, Color.green );
    }
}

在这种情况下,宽度是 4,所以基本上是图片中的 (n-1) 个点/圆。

大小为 3,这只是 2d 数组的长度,因为在这种情况下有 4 个圆圈,每个圆圈之间会有 3 个数字

事件是二维数组,其数据包含数字

drawCircle 方法的签名是 (x, y, radius, color)

drawString 方法的签名是 (text, x, y color)

我相信部分问题也是画圆。基本上我认为这与我用来确定圆圈和文本的 x、y 坐标的垃圾公式有关。任何帮助表示赞赏,谢谢。

标签: javaswing

解决方案


您也可以将圆的坐标存储在二维数组中,并使用它来查找字符串的位置。需要注意的一点是,由于drawCircle某种原因,该方法不会以给定的中心绘制圆(您给出的坐标实际上是左上角)。

Point[][] circleCoords = new Point[width][width]; //suppose Point class has x and y coords 

for (int i = 0; i < width; i++) {
   for (int j = 0; j < width; j++) {
    //the -15 actually centers the circle to the coordianates
    circleCoords[i][j] = new Point((j + 1) * 125 - 15, (i + 1) * 125 -15);
    canvas.drawCircle(circleCoords[i][j].x , circleCoords[i][j].y, 15, Color.white);
   }
}

for (int r = 0; r < width-1; r++) {
   for (int c = 0; c < width-1; c++) {
    //calculate coords from circleCoords array: halfway between them
    int xCoord = (circleCoords[r][c].x + circleCoords[r+1][c].x)/2; 
    int yCoord = (circleCoords[r][c].y + circleCoords[r][c+1].y)/2;
    //wont be out of bounds, becouse this runs to width-1
    canvas.drawString(events[r][c], xCoord, yCoord, Color.green );
    }
 }

这实际上仍然不会完全居中,因为 drawString 也会使用左上角的坐标,而不是中心点。也许我算错了一些东西,但这应该给你一个想法:不要独立计算坐标,而是重新使用圆坐标。


推荐阅读