简体   繁体   中英

Swing timer not working

I am creating an arcade game for a class. The game is Columns. I am trying to make all free floating blocks fall once per second. My code to make them fall works, but the timer does not. Here are the relevant portions of my code.

These first two appear in my BlockManager object that I use to manage the internal logic

public void play(){
    t = new Timer(1000, this);
    t.start();
    }
public void actionPerformed(ActionEvent e) {
    for(int v = 0;v < this.x; v++){
        if(v > this.x || v < 0){
            break;
            }
            for(int b = 0;b < this.y ;b++){
                this.gameScreen.get(v).get(b).setActive(true);
            }
        }
        for(int i = 0;i < this.x; i++){
            if(i > this.x || i < 0){
                break;
            }
            for(int j = 0;j < this.y ;j++){
                if(this.gameScreen.get(i).get(j).getActive() == true){
                    if(j + 1 < this.y){
                        if(this.gameScreen.get(i).get(j+1).toString().equals(".")){ 
    Collections.swap(this.gameScreen.get(i), j, j+1);
    this.gameScreen.get(i).get(j+1).setActive(false);
                        }
                    }
                }
            }
        }
    }

this is the main method that is another file. 

public static void main(String[] args){
    ColumnsUI Col = new ColumnsUI(9,9);
    Col.game.nextBlock();
    Col.gw.add(Col.show);
    Col.game.play();
}

The columns UI object is a simple method that paints based on the internal logic. I doubt that it has anything to do with the timer malfunction as it worked when I manually called the contents of actionPerformed.

Thanks for any help!

The actionPerfomed gets called when some event happens. You should create a separate class for the timer. Like in this code, of course the Task class must be replaced by your code, that moves the bricks.

Timer timer = new Timer();

// Start in 1 second and then all 5 seconds forever repatedly
timer.schedule( new Task(), 1000, 5000 );

Please have a look at the Java API for TimerTask

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM