gpt4 book ai didi

java - 计算单元格大小并绘制(中间有线)

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:30:23 26 4
gpt4 key购买 nike

我想绘制一个网格并在单元格中绘制内容(为了简单起见,只需填充它们)。总的来说,我几乎只在某些面板尺寸下工作,单元格距离它应该放置的位置大约 1 个像素(重叠线)。TBH 我还没有真正做足够的计算来自己找到答案,所以我对此表示歉意,不过我真的不太确定如何解决这个“错误”。

无论如何,这是代码:

public class Gui extends JFrame {

public static void main(String[] args) {
new Gui().setVisible(true);
}

public Gui() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
add(new JPanel() {
public static final int SIZE = 3;
/** Line thickness ratio to a block */
public static final float LINE_THICKNESS = 0.1f;

/** @return the width of a block. */
protected final int getBlockWidth() {
return getWidth() / SIZE;
}

/** @return the height of a block. */
protected final int getBlockHeight() {
return getHeight() / SIZE;
}

/** @return the width of a cell. */
protected final int getCellWidth() {
return (int) Math.ceil(getBlockWidth()*(1-LINE_THICKNESS));
}

/** @return the height of a cell. */
protected final int getCellHeight() {
return (int) Math.ceil(getBlockHeight()*(1-LINE_THICKNESS));
}

@Override
public void paintComponent(Graphics g) {
g.setColor(new Color(0, 0, 255, 100));
int lineWidth = (int) (LINE_THICKNESS * getBlockWidth());
int lineHeight = (int) (LINE_THICKNESS * getBlockHeight());
for(int i = 0; i <= SIZE; i++) {
g.fillRect(i * getBlockWidth() - lineWidth / 2, 0, lineWidth, getHeight());
g.fillRect(0, i * getBlockHeight() - lineHeight/2, getWidth(), lineHeight);
}
g.setColor(new Color(255, 0, 0, 100));
for(int i = 0; i < SIZE; i++) {
for(int j = 0; j < SIZE; j++) {
int x = j * getBlockWidth() + lineWidth/2;
int y = i * getBlockHeight() + lineHeight/2;
Graphics temp = g.create(x, y, getCellWidth(), getCellHeight());
drawCell(temp, i, j);
}
}
}

private void drawCell(Graphics g, int i, int j) {
g.fillRect(0, 0, getCellWidth(), getCellHeight());
}
});
setLocation(new Point(500, 200));
setSize(new Dimension(600, 600));
}
}

如果您运行它,您可能会明白我的意思。我想不出一个好的语言解释。起初我以为我必须将 + 1 添加到 x 和 y,因为我想在线旁边绘制,但这(显然)只是将问题转移到另一边。

用更大的 SIZE(例如 30)运行它会给我另一个错误,它会为两侧提供开放空间。我知道(或假设)这是因为我使用的是整数,不过这没什么大不了的。但总是欢迎提供更好的方法(一般而言)的提示。

最佳答案

有几种方法可以解决这个问题。我不会给你代码,因为我相信(根据你提出问题的方式)你是喜欢自己思考和解决问题的人之一。

首先:先在整个面板上画背景,再画线条。不会有白线,绘图会稍微快一些。

第二种方式:绘制顺序很重要。您可以安全地先绘制背景(即使它重叠),然后用边框覆盖它。

第三种方式:不使用整数。使用花车或 double 。你所有的麻烦都会烟消云散。

第四种方式:计算余数。你可以预测什么时候画线,什么时候不画,想一想。预测并适当绘制。

关于java - 计算单元格大小并绘制(中间有线),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19308513/

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