其實你需要兩個for循環一個用於行和一個用於列而不是你只使用一個,這不足以繪製網格。
我已經繪製了網格作爲我的任務工作,我已經與你分享。這將幫助你得到找到您的編碼問題...
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);
}
}
你可以參考這個: http://stackoverflow.com/questions/15421708/how-to-draw-grid-using-swing-class-java-and-detect-mouse-position-when-點擊並 –