使用Timer更新点的图形

Zac*_*tén 4 java graphics swing timer paintcomponent

在我提出我的问题之前,我对任何不一致表示歉意.我是相当新的.我正在制作一款现在看起来像这样的游戏(图片并不重要): 我的游戏

红点应该向右移动,他们用计时器做到这一点.这很好用.图形不会更新,所以我必须来回拖动窗口的一侧,看看我的点在移动.我该怎么做才能解决这个问题?

我的mainclass中的paintcomponent方法:

    public void paintComponent(Graphics g){
    super.paintComponent(g);
    for (int x = 0; x < SomeInts.amount; x++){
        for (int y = 0; y < SomeInts.amount; y++){
            tile[x][y].colorBody(g, x, y);              
            Tower temp;
            for (int i = 0; i < towers.size(); i++){        
                temp = towers.get(i);
                temp.colorBody(g, tile[x][y].getSize());
                temp.guard.colorBody(g, tile[x][y].getSize());                        
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的红点课.也称为Guard类:

public class Guard {
int x, y, size = 10, towerx, towery;
Timer timer;
public Guard(int towerx1, int towery1){
    towerx = towerx1;
    towery = towery1;
    x = towerx + 1;
    y = towery;
    new Timer().schedule(new MyTask(), 1000, 1000);
}

public void colorBody(Graphics g, int tilesize){
    g.setColor(new Color(255, 0, 0));
    g.fillOval(x * tilesize + tilesize / 4, y * tilesize + tilesize / 4, size, size);       
}

public class MyTask extends TimerTask {
    public void run() {
        x++;
    }
}
Run Code Online (Sandbox Code Playgroud)

}

感谢您的时间.

Roy*_*Roy 5

我在这里猜测一下,但我认为你需要调用repaint()方法来查看你所做的更改.