私は(ちょうどそれらを埋める簡単なものを維持するために)グリッドを描画し、細胞内のものを描きたいです。 全体的には、一部のパネルサイズでしか動作しません。セルは、配置する場所(線が重なる部分)から約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));
}
}
あなたはおそらく、私が何を意味するかわかります。私は言葉で良い説明を考えることができません。最初は、xとyに+ 1を加えなければならないと思ったので、私はその線の隣に描画したいと思っていましたが、これは(明らかに)問題をもう一方の側にシフトするだけです。 (30など)SIZE大きなでこれを実行する
は私にそれを脇にオープンスペースを与える別のバグを与えます。私は整数を使用しているのでこれがわかっている(または仮定している)が、それはあまりにも大きな問題ではない。しかし、(一般的に)より良いアプローチのヒントはいつでも歓迎します。
+1。 – Dariusz