简体   繁体   中英

JButton stuck when clicked (because i start recursive function in ActionListener)

I'm doing a board game in java, and I want to make a start button to start the game. the main function is a recursive function (gameloop), I call the function in the ActionListener and when I click the button it gets stuck.

ActionListener startListener = new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        gameFrame.remove(startB);
        gameFrame.add(boardPanel, gbc);
        gameFrame.revalidate();
        Game.gameLoop(); //the main recursive function
    }
};

Edit: I used SwingWorker and it works just fine, thanks for you help

Try something like this:

@Override
        public void actionPerformed(ActionEvent e) {

            gameFrame.remove(startB);
            gameFrame.add(boardPanel, gbc);
            gameFrame.revalidate();
            new Thread(){
                   public void run(){
                           Game.gameLoop(); //the main recursive function
                   }
            }.start();

        }

This is a complete wrong design.

First of all: actionPerformed() should trigger some action, but never run a game loop. actionPerformed() should return ASAP: It is not meant to perform complicated actions. Ideally put the game loop into an own thread and implement actionPerformed() in such a way that it passes actions to the game loop and then immediately returns.

Second: A game loop should be implemented iteratively, not as a recursive function. (That's why it is called "game loop" in th first place.) It does not make sense to implement it recursively as game loops tend to run quite long and a recursive concept would consume more and more stack memory and will fail at some point - and typically quite soon.

I recommend a complete redesign of your software. Then you won't have any troubles with JButton .

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