Calling a method from a JButton is freezing a JFrame?

前端 未结 2 1668
执念已碎
执念已碎 2021-01-26 03:30

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\'

2条回答
  •  长发绾君心
    2021-01-26 04:12

    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

提交回复
热议问题