JPanel doesn't repaint if repaint() is called within JFrame code

前端 未结 2 1183
清酒与你
清酒与你 2021-01-19 04:34

I have a class Forest and CellularJPanel, which extends JPanel and displays Forest. I wrote a primitive code to create

2条回答
  •  清歌不尽
    2021-01-19 05:13

    Your problem is having a while(true) on the Event Dispatch Thread which will block anything related to UI because UI events aren't getting handled anymore.

    The event dispatch thread (a single thread) works down a queue of UI event messages, until it handles the one where your while(true) loop is running. It then blocks any further processing because there's an infinite loop on it. Calling SwingUtilities.invokeLater from that loop won't help because it posts an event to the event dispatch thread, which is blocked in the while(true) loop.

    So remove that loop, instead use a javax.swing.Timer to time your events. In the timer event, change the state of your UI and call for a repaint. The timer event will be synchronized with the UI thread, so changing state of UI components is allowed.

提交回复
热议问题