【发布时间】:2019-01-24 05:59:59
【问题描述】:
我正在尝试创建一个窗口框架来显示游戏窗口。我在我的GameWindow 类中扩展了JFrame,并创建了两个方法: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()。我还尝试在revalidate、update 等drawBackground 和drawGrid 中使用许多不同的组合和顺序。这些尝试似乎都不起作用。我该如何解决这个问题?
【问题讨论】:
标签: java swing graphics jframe