从JButton调用方法会冻结JFrame吗? [英] Calling a method from a JButton is freezing a JFrame?

查看:74
本文介绍了从JButton调用方法会冻结JFrame吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个班级做一个基本的Pong游戏.我正在工作Pong,并且在启动时有GUI显示,很遗憾,我似乎无法从开始的JButton开始游戏.我已在代码中指出问题所在,并删除了不相关的代码.

I'm doing a basic Pong game for a class. I have the Pong working, and I have a GUI display on startup, unfortunately I can't seem to start the game from the start JButton. I've commented where the problem is on the code, and removed irrelevant code.

 frame.add(GUIPanel);
        JButton startButton = new JButton("Start!");     
        GUIPanel.add(startButton, BorderLayout.CENTER);
        startButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
         { 
             frame.getContentPane().remove(GUIPanel);
             frame.validate();
             frame.repaint();

             drawPanel = new DrawPanel();
             drawPanel.requestFocus();
             frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
              //This is the part that freezes it, everything else works fine
              //except that the playGame method isn't called. If I remove the whole
              //startButton and whatnot I can call playGame and it works perfectly.                                                                                    
              playGame();          
           }
         }); 
         }

有什么想法吗?

推荐答案

Swing是一个单线程框架.

Swing is a single threaded framework.

也就是说,对UI的所有交互和修改都应在事件调度线程的上下文内进行.阻塞此线程的任何事物都将阻止其处理,尤其是重画请求和用户输入/交互.

That is, all interactions and modifications to the UI are to be made from within the context of the Event Dispatching Thread. Anything that blocks this thread will prevent it from processing, amongst other things, repaint requests and user input/interactions.

我的猜测是playGame使用的是类似Thread.sleep或某种类型的while(true)的东西,并且阻塞了EDT,导致您的程序看起来好像被冻结了

My guess is that playGame is using something like Thread.sleep or some kind of while(true) and is blocking the EDT, causing your program to appear as if it's frozen

请仔细阅读 Swing中的并发,以了解更多详细信息.

Have a read through Concurrency in Swing for more details.

一个简单的解决方案是使用摇摆Timer 充当游戏循环.每次打勾时,您将更新游戏状态并调用(类似)游戏组件上的repaint

A simple solution would be to use a Swing Timer to act as you game loop. Each time it ticks, you would update the state of your game and call (something like) repaint on you game's component

这篇关于从JButton调用方法会冻结JFrame吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆