2016-07-07 18 views
1

我想绘制一个网格。列x行例如是5x6。我的问题是,东部和南部的线结束超过给定的列和行值。这不是很大,也许只有一个毫米,但仍然很烦人。我希望网格看起来像一个矩形,在上面的情况下,有20个单元格。我的代码中的错误在哪里?下面是描述这个有缺陷的网格的代码片段。谢谢!为什么我的网格上的线的末端超过了该网格的给定宽度和高度?

package Main; 

import java.awt.Dimension; 

import javax.swing.JFrame; 

public class GridMain { 

    public static void main(String[] args) { 
     JFrame jframe = new JFrame(); 
     jframe.setPreferredSize(new Dimension(640, 730)); 
     jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     Mypanel mypanel = new Mypanel(5,6); 
     jframe.add(mypanel); 
     jframe.pack(); 
     jframe.setVisible(true); 
    } 
} 
package Main; 

import java.awt.Graphics; 

import javax.swing.JPanel; 

public class Mypanel extends JPanel { 
    /** 
* 
*/ 
    private static final long serialVersionUID = 1L; 
    private int height; 
    private int width; 
    private int gapBetweenPoints = 20; 
    private int gapBetweenFrameAndGrid=15; 
    public Mypanel(int columns, int rows) { 
     width = columns; 
     height = rows; 
    } 

    protected void paintComponent(Graphics g) { 
     for (int i =0 ; i < height; i++) { 
      g.drawLine(gapBetweenFrameAndGrid, i * gapBetweenPoints 
        + gapBetweenFrameAndGrid, width * gapBetweenPoints, i 
        * gapBetweenPoints + gapBetweenFrameAndGrid); 
     } 
     for (int i = 0; i < width; i++) { 
      g.drawLine(i * gapBetweenPoints + gapBetweenFrameAndGrid, 
        gapBetweenFrameAndGrid, i * gapBetweenPoints + gapBetweenFrameAndGrid, 
        height * gapBetweenPoints); 
     } 
    } 
} 
+0

滑稽,当我在第二循环中,我得到。减去5从(宽度* gapBetweenPoints)在第一for循环和从(高度* gapBetweenPoints)我想要的结果..但这显然不是我们如何做的事情:-) – melar

回答

2

小心你从哪里得到起点;我不会达到宽度(高度),但只有宽度-1 /高度-1。所以下面的代码:

for (int i =0 ; i < height; i++) { 
     g.drawLine(gapBetweenFrameAndGrid, i * gapBetweenPoints 
       + gapBetweenFrameAndGrid, gapBetweenFrameAndGrid+(width-1) * gapBetweenPoints, i 
       * gapBetweenPoints + gapBetweenFrameAndGrid); 
    } 
    for (int i = 0; i < width; i++) { 
     g.drawLine(i * gapBetweenPoints + gapBetweenFrameAndGrid, 
       gapBetweenFrameAndGrid, i * gapBetweenPoints + gapBetweenFrameAndGrid, 
       gapBetweenFrameAndGrid+(height-1) * gapBetweenPoints); 
    } 

一般而言

for (int i =0 ; i < height; i++) { 
     g.drawLine(startingX, i * gapBetweenPoints 
       + gapBetweenFrameAndGrid, startingX+(width-1) * gapBetweenPoints, i 
       * gapBetweenPoints + gapBetweenFrameAndGrid); 
    } 
    for (int i = 0; i < width; i++) { 
     g.drawLine(i * gapBetweenPoints + gapBetweenFrameAndGrid, 
       startingY, i * gapBetweenPoints + gapBetweenFrameAndGrid, 
       startingY+(height-1) * gapBetweenPoints); 
    } 
+0

thx很多!解决了我的问题。只是为了澄清:在第二个代码中,在第一个循环中,为什​​么不添加startX到(i * gapBetweenPoints)而不是添加gapBetweenFrameAndGrid?我错过了什么?第二个循环也是如此 – melar

相关问题