我有一个类Forest
和CellularJPanel
,它扩展了JPanel
并显示Forest
。我写了一个原始代码来创建JFrame
,Forest
,CellularJPanel
并将CellularJPanel
添加到JFrame
。接下来是一个无限循环,它使Forest
更新和CellularJPanel
重绘。如果在JFrame代码中调用repaint(),则JPanel不会重新绘制
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
的初始状态,因为paintComponent
被调用一次,当jFrame.setVisible(true)
被调用。然后while
循环正在执行,但CellularJPanel
不重画,paintComponent
不称为。我不知道为什么,也许我应该使用SwingUtilities.invokeLater(...)
或java.awt.EventQueue.invokeLater
,但我已经尝试过它,它不起作用,我做错了什么。
有什么建议吗?
P.S. 我的目标是在单击按钮的同一个UI JFrame中显示CellularJPanel
。但即使我将此面板添加到主UI JFrame,它也不起作用。
顺便说一句,欢迎来到StackOverflow! – Krease
谢谢:) StackOverflow是令人难以置信的有用! – Darko