Calling a method from a JButton is freezing a JFrame?

帅比萌擦擦* 提交于 2019-12-02 18:21:10

问题


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();          
           }
         }); 
         }

any ideas?


回答1:


Swing is a single threaded framework.

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.

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

Have a read through Concurrency in Swing for more details.

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




回答2:


It looks like you've got a parenthesis that doesn't belong next to your second to last semicolon. Try removing it.



来源:https://stackoverflow.com/questions/23508354/calling-a-method-from-a-jbutton-is-freezing-a-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!