首先调用JPanel repaint()方法会创建不需要的背景图像

时间:2013-09-20 19:26:42

标签: java swing jpanel repaint

我已将Sokoban克隆编程为我的学习计划项目。自升级到JDK 7以来,我遇到以下问题:我第一次在我的JPanel上调用repaint()方法时,我的JPanel右侧出现了“阴影图像”,如下所示: 之前: 之后:

我不知道造成这种情况的原因,所以不太清楚要添加哪些代码。 这是paint()方法:

public void paint(Graphics g) {

    int x;
    int y;

    // draw column
    for (int k = 0; k < field.getField().length; k++) {
        y = (tileWidth * k); // Get y coordinate

        // draw line
        for (int l = 0; l < field.getField()[0].length; l++) {
            FieldObj now = field.getField()[k][l];

            x = (tileWidth * l); // Get x coordinate

            // Wall
            if (now instanceof Wall)
                g.drawImage(Wall, x, y, tileWidth, tileWidth, null);
            // Box
            else if (now instanceof Box && ((Box) now).getStandingOnGoal())
                g.drawImage(BoxOnG, x, y, tileWidth, tileWidth, null);
            else if (now instanceof Box)
                g.drawImage(Box, x, y, tileWidth, tileWidth, null);
            // Man on Goal
            else if (now instanceof Man
                    && field.getMan().getStandingOnGoal()
                    && field.getMan().getOr() == 0)
                g.drawImage(ManGU, x, y, tileWidth, tileWidth, null);
            else if (now instanceof Man
                    && field.getMan().getStandingOnGoal()
                    && field.getMan().getOr() == 1)
                g.drawImage(ManGL, x, y, tileWidth, tileWidth, null);
            else if (now instanceof Man
                    && field.getMan().getStandingOnGoal()
                    && field.getMan().getOr() == 2)
                g.drawImage(ManGR, x, y, tileWidth, tileWidth, null);
            else if (now instanceof Man
                    && field.getMan().getStandingOnGoal()
                    && field.getMan().getOr() == 3)
                g.drawImage(ManGD, x, y, tileWidth, tileWidth, null);
            // Man
            else if (now instanceof Man && field.getMan().getOr() == 0)
                g.drawImage(ManU, x, y, tileWidth, tileWidth, null);
            else if (now instanceof Man && field.getMan().getOr() == 1)
                g.drawImage(ManL, x, y, tileWidth, tileWidth, null);
            else if (now instanceof Man && field.getMan().getOr() == 2)
                g.drawImage(ManR, x, y, tileWidth, tileWidth, null);
            else if (now instanceof Man && field.getMan().getOr() == 3)
                g.drawImage(ManD, x, y, tileWidth, tileWidth, null);
            // Floor
            else if (now instanceof Floor && ((Floor) now).getGoal())
                g.drawImage(Goal, x, y, tileWidth, tileWidth, null);
            else
                g.drawImage(Floor, x, y, tileWidth, tileWidth, null);
        }
    }

}

有什么建议吗?你想看到的其他代码? 我会感激任何帮助。 甲

1 个答案:

答案 0 :(得分:2)

不要覆盖paint()!!!

通过覆盖paintComponent()方法完成自定义绘制,第一个语句通常应该是:

super.paintComponent(g);

确保在绘画之前清除背景。

阅读Custom Painting上的Swing教程了解基础知识。