【发布时间】:2016-02-13 16:41:27
【问题描述】:
我有一个类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。然后 while 循环正在执行,但 CellularJPanel 不会重新绘制,paintComponent 不会被调用。我不知道为什么,也许我应该以某种方式使用SwingUtilities.invokeLater(...) 或java.awt.EventQueue.invokeLater,但我已经尝试过了,但它不起作用,我做错了什么。
有什么建议吗?
附:
我的目标是在同一个 UI JFrame 中显示CellularJPanel,点击该按钮。但即使我将此面板添加到主 UI JFrame,它也不起作用。
【问题讨论】:
-
对了,欢迎来到 StackOverflow!
-
谢谢 :) StackOverflow 非常有用!