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

前端 未结 2 1159
清酒与你
清酒与你 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:01

    There is a single UI thread that draws things - it's also the one that handles button clicks. In swing, this is called the event dispatch thread. If The UI thread is busy running a while loop, it can't paint.

    You can quickly verify this by making your button click handler run only a single iteration of your loop (without the sleep): forest.update(); forestJpanel.repaint();

    You can auto update from a separate thread (like Timer) that calls repaint/sleep in a loop.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题