2016-07-07 5 views
1

グリッドを描画しようとしています。列xの行は、例えば、5x6である。私の問題は、東と南の行末が指定された列と行の値を超えていることです。それは大きくないかもしれませんが、ちょうど1ミリメートルかもしれませんが、それでも迷惑です。私は上記の場合、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

面白い、私は(幅* gapBetweenPoints)から5をsubstract最初のループのために、私が得る第二のループ内(高さ* gapBetweenPoints)から結果は私が望む..しかし、それは明らかに私たちが何をするかではありません:-) – melar

答えて

2

出発点はどこにあるか注意してください。私は幅(高さ)に達することはありませんが、幅-1 /高さ-1にしか達しません。したがって、次のコード:一般

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

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

+0

thxたくさん!それは私の問題を解決する。 2番目のコードでは、最初のループで、なぜgapBetweenFrameAndGridを追加するのではなく、beginXを(i * gapBetweenPoints)に追加しないのですか?私は何が欠けていますか?同様に、2番目のループのために行く – melar

関連する問題