我在制作这个网格时从顶部开始画10个像素,从画面左边开始画10个像素,我遇到了一些麻烦。
我可以通过将this.getY()+ 10增加到更高的数字来做到这一点,只是想知道为什么如果删除+ 10它被抽出屏幕。
忽略变量名称和我刚刚把它放在一起的任何格式
package griddrawing;
import java.awt.*;
import javax.swing.*;
public class Grid extends JFrame
{
private int TILEWIDTH;
private int TILEHEIGHT;
private int COLS;
private int ROWS;
private int defaultX;
private int defaultY;
private int currentX;
private int currentY;
public Grid()
{
setSize(800,400);
TILEWIDTH = 30;
TILEHEIGHT = 30;
COLS = 10;
ROWS = 10;
defaultX = this.getX() + 10;
defaultY = this.getY() + 10;
currentX = 0;
currentY = 0;
}
@Override
public void paint(Graphics g)
{
super.paint(g);
currentX = defaultX;
currentY = defaultY;
g.setColor(Color.black);
for(int i = 0; i < COLS; i++)
{
for(int k = 0 ; k < ROWS; k++)
{
g.drawRect(currentX - (TILEWIDTH / 2), currentY - (TILEHEIGHT / 2), TILEWIDTH, TILEHEIGHT);
g.drawString("" + k, currentX, currentY);
currentY += TILEWIDTH;
System.out.println("COL: " + i + " ROW: " + k + " Current X: " + currentX + " Current Y: " + currentY);
}
currentY = defaultY;
currentX += TILEHEIGHT;
}
}
}
答案 0 :(得分:3)
而不是两者:
paintComponent(Graphics)
或JComponent
的{{1}}方法。 JPanel
或覆盖相同的方法。 theComponent.setPreferredSize(Dimension)
。 那个地段应该意味着你不再需要来解释任何偏移(可能会因平台或PLAF而改变)。