我正在嘗試創建一個窗口框架來顯示游戲窗口。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
提交
取消