[英]Swing drawing a grid. Wierd result
所以我正在使用graphics2d在JPanel上繪制網格。
但是,當我調整窗口大小時,它將以奇怪的結果結束。
@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();
}
因此,與其繪制8x8正方形,不如繪制水平矩形(getSize()。width()x8)。
更新
我正在繪制一個將填充整個JPanel的網格。 因此,當窗口調整大小時,網格將擴展並且可以正常工作。 但有時會繪制出奇怪的形狀。 網格單元的大小恆定為8x8
改成這個
for(int x = 0; x < 8; x++){
for(int y = 0; y < 8; y++){
更新:如果您想在增加幀數時使用寬單元格
int cellWidth=getSize().width/8;
int cellHeight=getSize().height/8;
和
g2d.fillRect(cellWidth*x, cellHeight*y, cellWidth, cellHeight);
使用下一個修復程序:
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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.