我有一个类Forest和CellularJPanel,它扩展了JPanel并显示了Forest.我写了一个原始代码来创建JFrame,Forest,CellularJPanel并将CellularJPanel添加到JFrame.接下来是一个无限循环,它使Forest更新和CellularJPanel重新绘制.
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)
{
}
}
这是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);
}
}
如果我在main()方法中使用上面的代码,那么一切正常,
CellularJPanel重新绘制,paintComponent()被正常调用.
如果我将相同的代码粘贴到UI JFrame按钮单击事件方法,则新的JFrame会显示甚至显示Forest的初始状态,因为在调用jFrame.setVisible(true)时会调用paintComponent.然后在执行循环时,但是CellularJPanel没有重新绘制,则不会调用paintComponent.我不知道为什么,也许我应该以某种方式使用SwingUtilities.invokeLater(…)或java.awt.EventQueue.invokeLater,但我已经尝试过它们并没有用,我做错了.
有什么建议?
附:
我的目标是在同一个UI JFrame中显示CellularJPanel,单击该按钮.但即使我将此面板添加到主UI JFrame,它也不起作用.