我正在尝试创建一个窗口框架来显示游戏窗口。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。这些尝试似乎都没有奏效。我该如何解决这个问题?
1 回答

Qyouu
TA贡献1786条经验 获得超11个赞
好吧,Graphics g = this.getGraphics();
这将是一个很好的起点。由于repaint
只是安排了与 一起发生的绘制过程,因此RepaintManager
所有使用的代码getGraphics
都将被忽略。
这不是定制绘画的工作方式。 getGraphics
可以返回null
并且充其量只是上一个油漆周期的快照,您在其上绘制的任何东西都将在下一个油漆周期中被擦干净。
另外,不要使用您没有创建dispose
的上下文,在某些系统上,这将阻止其他组件使用它Graphics
首先查看在 AWT 和 Swing中执行自定义绘画和绘画,以更好地了解绘画的工作原理以及您应该如何使用它。
您可能还想通读 Swing 中的并发性和如何使用 Swing 计时器,以了解有关创建“主循环”以恒定速率更新 UI 的想法,因为 Swing 是单线程的,不是线程安全的
添加回答
举报
0/150
提交
取消