【问题标题】:Why do JFrame's update, revalidate, and repaint not update the window?为什么JFrame的update、revalidate、repaint不更新窗口?
【发布时间】:2019-01-24 05:59:59
【问题描述】:

我正在尝试创建一个窗口框架来显示游戏窗口。我在我的GameWindow 类中扩展了JFrame,并创建了两个方法: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()。我还尝试在revalidateupdatedrawBackgrounddrawGrid 中使用许多不同的组合和顺序。这些尝试似乎都不起作用。我该如何解决这个问题?

【问题讨论】:

    标签: java swing graphics jframe


    【解决方案1】:

    嗯,Graphics g = this.getGraphics(); 将是一个不错的起点。由于repaint 只是安排与RepaintManager 一起发生的绘制通道,所有使用getGraphics 的代码都将被忽略。

    这不是自定义绘画的工作方式。 getGraphics 可以返回 null 并且充其量只是上一个绘画周期的快照,您在上面绘画的任何东西都会在下一个绘画周期中被擦干净。

    另外,不要在 Graphics 未创建的上下文中使用 dispose,在某些系统上这会阻止其他组件使用它

    首先查看Performing Custom PaintingPainting in AWT and Swing,以更好地了解绘画的工作原理以及您应该如何使用它。

    您可能还想通读 Concurrency in SwingHow to Use Swing Timers 以了解有关创建“主循环”以恒定速率更新 UI 的想法,因为 Swing 是单线程而不是线程安全

    【讨论】:

    • 嗯.. 刚刚注意到您的“300K”代表。标签非常迫在眉睫。仅增加 75(?)个代表。
    • 顺便说一句-您有大量的代表可以闲置。我挑战你,一旦达到 300K,就一个 Java 相关问题的优秀答案发布 500 的赏金。代表
    • 如果可以的话会+50;链接非常有用,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多