在java中绘制网格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19166562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Drawing a grid in java
提问by Christian Baker
I am trying to create a Cartesian Grid using a for loop. Below is part of my code so far; when I run it, it does not make a series of lines, but rather it produces a window that has what appears to be a white panel and it slows down my computer considerably. In fact, I have to start task manager and End Task it, because it won't even close normally.
我正在尝试使用 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);
}
}
回答by David Conrad
The increment in your for
loop is wrong. Instead of
for
循环中的增量是错误的。代替
i = i++
It should be simply
应该很简单
i++
The postincrement operator returns the old value of i,
which is being assigned back to i,
so i
never actually changes.
后增量运算符返回i,
被分配回的旧值,i,
因此i
永远不会实际更改。
回答by Bhushankumar Lilapara
Actually you need two for loop one for row and and one for column instead you just used one, that is not enough to draw grid.
实际上,您需要两个 for 循环,一个用于行,一个用于列,而您只使用了一个,这不足以绘制网格。
I have drawn grid as my assignment work, I have share it with you. It will help you to get find problem in your coding...
我已经画了网格作为我的作业,我已经和你分享了。它将帮助您在编码中找到问题...
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);
}
}
回答by Two_Years_Experience
hey Guys i just used the little slice of your p to try and fix it and I just created a string art construction here is the code if you want to do it as well.int width = getWidth(); int height = getHeight();
嘿伙计们,我只是用你的 p 的一小部分来尝试修复它,我刚刚创建了一个字符串艺术结构,如果你也想这样做,这里是代码。 int width = getWidth(); int height = getHeight();
int xstart=0;
for(int i = 1; i <= 10; i++)
{
xstart = i*(height/10);
page.drawLine(xstart, 0, width, xstart);
}