亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么JFrame的update、revalidate、repaint不更新窗口?

為什么JFrame的update、revalidate、repaint不更新窗口?

Cats萌萌 2022-05-21 20:27:07
我正在嘗試創建一個窗口框架來顯示游戲窗口。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 是單線程的,不是線程安全的


查看完整回答
反對 回復 2022-05-21
  • 1 回答
  • 0 關注
  • 236 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號