简体   繁体   English

单击时 JButton 卡住(因为我在 ActionListener 中启动递归函数)

[英]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.我正在用java做一个棋盘游戏,我想制作一个开始按钮来开始游戏。 the main function is a recursive function (gameloop), I call the function in the ActionListener and when I click the button it gets stuck.主函数是一个递归函数(gameloop),我在 ActionListener 中调用该函数,当我单击按钮时它会卡住。

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编辑:我使用了 SwingWorker,效果很好,谢谢你的帮助

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()应该触发一些动作,但永远不要运行游戏循环。 actionPerformed() should return ASAP: It is not meant to perform complicated actions. actionPerformed()应该尽快返回:它并不意味着执行复杂的操作。 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.理想情况下,将游戏循环放入自己的线程中,并以将动作传递给游戏循环然后立即返回的方式实现actionPerformed()

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 .那么你就不会在JButton遇到任何麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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