为了账号安全,请及时绑定邮箱和手机立即绑定

为什么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 关注
  • 249 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号