猿问

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

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


Cats萌萌
浏览 250回答 1
1回答

Qyouu

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

相关分类

Java
我要回答