I want to draw a grid and draw material in the cells (so that everything is simple, just fill them). In general, it works for me quite a lot only in some panel sizes, where the cell is located about 1 pixel where it should be placed (overlapping the line). TBH I actually didnβt do enough calculation to possibly find the answer myself, so I apologize for this, I'm really not too sure how to approach this βerrorβ, though.
Anyway, here is the code:
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; public static final float LINE_THICKNESS = 0.1f; protected final int getBlockWidth() { return getWidth() / SIZE; } protected final int getBlockHeight() { return getHeight() / SIZE; } protected final int getCellWidth() { return (int) Math.ceil(getBlockWidth()*(1-LINE_THICKNESS)); } 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)); } }
If you run it, you'll probably see what I mean. I cannot come up with a good explanation in words. At first I thought that I needed to add + 1 to x and y, since I want to draw next to the line, but this (obviously) just carries the problem to the other side.
Doing this with a SIZE larger (e.g. 30) gives me another error that gives open space to the sides. I know (or guess), this is because I use integers, and this is not a big deal. But tips for a better approach (overall) are always welcome.