Reputation: 63
So i'am using graphics2d to draw a grid on a JPanel.
But when i resize the window it will end with weird results.
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
/*
* Draw the background
*/
boolean isWhite = false;
for(int x = 0; x < getSize().width/8; x++){
for(int y = 0; y < getSize().height/8; y++){
if(isWhite){
g2d.setColor(Color.white);
isWhite = false;
}else{
g2d.setColor(Color.LIGHT_GRAY);
isWhite = true;
}
g2d.fillRect(8*x, 8*y, 8, 8);
}
}
g2d.dispose();
}
So instead of drawing 8x8 squares it will draw horizontal rectangles (getSize().width()x8).
Update
I'am drawing a grid that will fill an entire JPanel. So when the window is resizing the grid will expand and that works. But it will draw weird shapes(Sometimes). The grid-cell have a constant size of 8x8
Upvotes: 2
Views: 102
Reputation: 10994
Use next fix:
boolean isWhite = false;
boolean isWhiteLastLine = isWhite;
for(int x = 0; x < getSize().height; x=x+8){
for(int y = 0; y < getSize().width; y=y+8){
if(y == 0){
isWhiteLastLine = isWhite;
}
if(isWhite){
g2d.setColor(Color.white);
}else{
g2d.setColor(Color.LIGHT_GRAY);
}
g2d.fillRect(y, x, 8, 8);
isWhite = !isWhite;
if(y+8 >= getSize().width){
isWhite = !isWhiteLastLine;
}
}
}
Upvotes: 2
Reputation: 57391
Change to this
for(int x = 0; x < 8; x++){
for(int y = 0; y < 8; y++){
UPDATE: if you would like wide cells when frame is increased use
int cellWidth=getSize().width/8;
int cellHeight=getSize().height/8;
and
g2d.fillRect(cellWidth*x, cellHeight*y, cellWidth, cellHeight);
Upvotes: 2