java 不重画_java – 如果在JFrame代码中调用repaint(),JPanel不重绘

我有一个类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,它也不起作用.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值