我正在尝试使用 for 循环创建笛卡尔网格。以下是到目前为止我的代码的一部分;当我运行它时,它不会生成一系列线条,而是生成一个带有白色面板的窗口,这会大大减慢我的计算机速度。事实上,我必须启动任务管理器并结束任务,因为它甚至不会正常关闭。
public void paintComponent(Graphics g)
{
int width = getWidth();
int height = getHeight();
super.paintComponent(g);
int xstart=0;
for(int i = 1; i <= 10; i = i++)
{
xstart = i*(width/10);
g.drawLine(xstart, 0, xstart, height);
}
}
Run Code Online (Sandbox Code Playgroud)
实际上你需要两个 for 循环,一个用于行,一个用于列,而不是你只使用了一个,这不足以绘制网格。
我画了网格作为我的作业,我和你分享。它将帮助您发现编码中的问题......

import java.awt.*;
class Grids extends Canvas {
int width, height, rows, columns;
Grids(int w, int h, int r, int c) {
setSize(width = w, height = h);
rows = r;
columns = c;
}
@Override
public void paint(Graphics g) {
int k;
width = getSize().width;
height = getSize().height;
int htOfRow = height / (rows);
for (k = 0; k < rows; k++) {
g.drawLine(0, k * htOfRow, width, k * htOfRow);
}
int wdOfRow = width / (columns);
for (k = 0; k < columns; k++) {
g.drawLine(k * wdOfRow, 0, k * wdOfRow, height);
}
}
}
public class DrawGrids extends Frame {
DrawGrids(String title, int w, int h, int rows, int columns) {
setTitle(title);
Grids grid = new Grids(w, h, rows, columns);
add(grid);
}
public static void main(String[] args) {
new DrawGrids("Draw Grids", 200, 200, 2, 10).setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)