【问题标题】:Loading bufferedImage disables JPanel's paintCompontent method加载 bufferedImage 会禁用 JPanel 的 paintCompontent 方法
【发布时间】:2012-06-03 07:04:41
【问题描述】:

我对 BufferedImage 和 JPanel 有一点问题。我正在创建一个带有一些 2d 动画的游戏。

基本上,我有一个动画处理程序,它将遍历图片,并且根据旋转也将正确显示它。但问题是 - 当我加载图片时,我的 Jpanel 不会画任何东西。如果我注释掉自定义绘制方法并不重要——paintComponent 方法不会绘制任何东西,而且它似乎跳过了paintCompontent 方法。即使游戏没有崩溃并且计时器仍在运行 - 它不会在扩展的 JPanel 中使用 paintComponent 方法。

包含计时器的类 - 通过 JPanel.repaint() 调用 JPanel;

这里是loadImg方法

/**
 * Test method to check animationHandler and bufferedImgs
 */
private void loadImages() {
    BufferedImage b_1;
    BufferedImage b_2;
    BufferedImage b_3;
    BufferedImage b_4;
    BufferedImage b_5;

    BufferedImage[] imgs = new BufferedImage[5];
    try {
        b_1 = ImageIO.read(new File("warlock1.png"));
        b_2 = ImageIO.read(new File("warlock2.png"));
        b_3 = ImageIO.read(new File("warlock3.png"));
        b_4 = ImageIO.read(new File("warlock4.png"));
        b_5 = ImageIO.read(new File("warlock5.png"));

        imgs[0] = b_1;
        imgs[1] = b_2;
        imgs[2] = b_3;
        imgs[3] = b_4;
        imgs[4] = b_5;

        animationHandler.addAnimation(imgs);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

干杯!

【问题讨论】:

  • 您能否发布您的 paintComponent() 方法,以便我们知道您是如何尝试绘制动画的?

标签: java swing jpanel bufferedimage


【解决方案1】:

您可能正在 Swing 事件线程或 EDT(事件调度线程)上加载图像,并且由于 EDT 负责所有 Swing 图形和用户交互,这将冻结您的 Swing 应用程序,直到加载完成。解决方案:在后台线程上加载图像,例如可以从 SwingWorker 对象获取。请查看Concurrency in Swing 教程以了解有关此主题的更多信息。

此外,如果可能,并且图像不是太大,通常最好加载图像一次,然后保存对它们或 ImageIcon 的引用。

最后,无论你做什么,都不要在paintComponent(...) 方法中加载图像。这种方法必须精益求精——尽可能快,并且它应该关注绘画而不是其他任何东西。否则您的程序的响应速度可能会变得非常缓慢。

另外,关于:

它不会在扩展的 JPanel 中使用 paintComponent 方法。

您可能想向我们展示此代码。

【讨论】:

  • 感谢它解决问题的帮助。通过创建自己的线程检查它!谢谢!有很多东西要学:>
  • 图像也是通过animationHandler加载的——不是在paintComponent中,也只有一次。然后在扩展 JPanel 的 Canvas 中完成绘画
  • @user1432962:您可以通过单击左侧的empty check mark 来接受此答案。供参考,另见此相关example
  • 是的,对不起。很好的例子!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-28
  • 1970-01-01
相关资源
最近更新 更多