2013-10-03 84 views
3

我正在尝试使用for循环创建笛卡尔网格。以下是我的代码到目前为止的一部分;当我运行它时,它并没有形成一系列的线条,而是产生了一个看起来像是白​​色面板的窗口,它显着降低了我的电脑速度。事实上,我必须启动任务管理器和结束任务,因为它甚至不能正常关闭。在java中绘制网格

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); 
    } 
} 
+0

你可以参考这个: http://stackoverflow.com/questions/15421708/how-to-draw-grid-using-swing-class-java-and-detect-mouse-position-when-点击并 –

回答

1

for循环中的增量错误。取而代之的

i = i++ 

应该是简单

i++ 

的后置运算符返回正在被分配回i,所以i实际上从未改变的i,旧值。

3

其实你需要两个for循环一个用于行和一个用于列而不是你只使用一个,这不足以绘制网格。

我已经绘制了网格作为我的任务工作,我已经与你分享。这将帮助你得到找到您的编码问题...

enter image description here

import java.awt.*; 
    import java.awt.event.*; 

    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; 
     } 
     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); 
     } 
    } 
0

嘿家伙我只是用你的p的小片,试图修复它,我只是创建了一个字符串建筑艺术这里是代码,如果你想这样做well.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); 
    }