JPanel does not redraw if repaint () is called in JFrame code

I have a class Forestand CellularJPanelthat extends JPaneland displays Forest. I wrote the code to create a primitive JFrame, Forest, CellularJPaneland add CellularJPanelin JFrame. The following is an endless loop that allows you to update Forestand CellularJPanelredraw.

    JFrame jFrame = new JFrame();          

    Forest forest = new Forest();
    CellularJPanel forestJPanel = new CellularJPanel(forest);

    jFrame.add(forestJPanel);

    jFrame.pack();
    //jFrame.setResizable(false);
    jFrame.setLocationRelativeTo(null);
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jFrame.setVisible(true);

    while (true)
    {
        try
        {
            forestJPanel.repaint();
            forest.update();
            forest.sleep(); // calls Thread.sleep(...)
        }   
        catch (InterruptedException e)
        {

        }
    }

Here is the class code CellularJPanel:

public class CellularJPanel extends JPanel
{
    private CellularAutomata cellularAutomata;

    public CellularJPanel(CellularAutomata cellularAutomata)
    {
        super();
        this.cellularAutomata = cellularAutomata;
        setPreferredSize(this.cellularAutomata.getDimension());
    }

    @Override
    public void paintComponent(Graphics g)     
    {
        super.paintComponent(g);            
        Graphics2D graphics2D = (Graphics2D)g;
        cellularAutomata.draw(graphics2D);
    }
}

If I use the code above in the method main(), then everything works fine, CellularJPanelrepaints, paintComponent()is called normally.

UI JFrame, click click, JFrame Forest, paintComponent , jFrame.setVisible(true). while, CellularJPanel , paintComponent . , , , - SwingUtilities.invokeLater(...) java.awt.EventQueue.invokeLater, , , - .

?

P.S. - CellularJPanel JFrame UI, . JFrame, .

+4
2

while(true) Event Dispatch Thread, , , .

( ) , , while(true). , . SwingUtilities.invokeLater , , while(true).

, , javax.swing.Timer . repaint. , .

+5

, - , . swing . while, .

, ( ): forest.update(); forestJpanel.repaint();

(, Timer), / .

+4

Source: https://habr.com/ru/post/1628651/


All Articles