我正在尝试创建一个窗口框架来显示游戏窗口。JFrame我在课堂上进行了扩展GameWindow并创建了两个方法:drawBackground,它用一个实心矩形填充屏幕,以及drawGrid,它使用 for 循环绘制连续的线来制作一个网格。这是我的代码。
public class GameWindow extends JFrame {
// instance variables, etc.
public GameWindow(int width, Color bgColor) {
super();
// ...
this.setVisible(true);
}
public void drawBackground() {
Graphics g = this.getGraphics();
g.setColor(bgColor);
g.fillRect(0, 0, this.getWidth(), this.getWidth());
// I suspect that the problem is here...
this.update(g);
this.revalidate();
this.repaint();
g.dispose();
}
public void drawGrid() {
Graphics g = this.getGraphics();
g.setColor(Color.BLACK);
for (int i = tileWidth; i < TILE_COUNT * tileWidth; i += tileWidth) {
g.drawLine(0, i * tileWidth, this.getWidth(), i * tileWidth);
g.drawLine(i * tileWidth, 0, i * tileWidth, this.getHeight());
}
// ... and here.
this.update(g);
this.revalidate();
this.repaint();
g.dispose();
}
}
但是,当我尝试在这样的程序中测试这个类时:
public class Main {
public static void main(String[] args) {
GameWindow game = new GameWindow(700);
game.drawBackground();
game.drawGrid();
}
}
框架出现在屏幕上但保持空白;既没有绘制背景也没有绘制网格。我试过Graphics g = this.getGraphics()了this.getContentPane().getGraphics()。drawBackground我还尝试在和drawGrid、等revalidate中使用许多不同的组合和顺序update。这些尝试似乎都没有奏效。我该如何解决这个问题?
Qyouu
相关分类