gpt4 book ai didi

java - 为什么网格上的线条末端超出了该网格的给定宽度和高度?

转载 作者:行者123 更新时间:2023-11-30 02:52:15 25 4
gpt4 key购买 nike

我正在尝试绘制一个网格。比如说,列 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);
}
}
}

最佳答案

要小心你的出发点;我不会达到宽度(高度),而只会达到宽度-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);
}

关于java - 为什么网格上的线条末端超出了该网格的给定宽度和高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38257030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com