I have a class Forest
and CellularJPanel
, which extends JPanel
and displays Forest
. I wrote a primitive code to create JFrame
, Forest
, CellularJPanel
and add CellularJPanel
to the JFrame
. Next is an infinite loop, which makes Forest
update and CellularJPanel
repaint.
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 a code of the CellularJPanel
class:
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 above code within main()
method, then everything works fine,
CellularJPanel
repaints, paintComponent()
is called normally.
If I paste the same code to UI JFrame button click event method, then new JFrame shows and even displays initial state of the Forest
, because paintComponent
is once called, when jFrame.setVisible(true)
is called. Then while
loop is being executed, but CellularJPanel
doesn't repaint, paintComponent
is not called. I have no idea why, maybe I should use SwingUtilities.invokeLater(...)
or java.awt.EventQueue.invokeLater
somehow, but I've tried them and it didn't work, I'm doing something wrong.
Any suggestions?
P.S.
My target is to display CellularJPanel
within the same UI JFrame, from which button was clicked. But even if I add this panel to main UI JFrame, it doesn't work.