程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

无法在图像上调用 getWidth()

发布于2022-12-05 23:34     阅读(808)     评论(0)     点赞(4)     收藏(4)


我有一个图像displayStartTextoriginalStartText因此初始化:

Image originalStartText = new ImageIcon(getClass().getClassLoader().getResource( "GAME/resources/ready_set_fight.gif" )).getImage();
Image displayStartText = originalStartText;

我尝试使用以下方法绘制以我的背景为中心的 displayStartText:

g2d.drawImage( displayStartText, (int)((bgDispWidth-displayStartText.getWidth())/2), (int)((bgDispHeight-displayStartText.getHeight())/2), null );

但是出现了一个我不明白的编译器错误

Gameplay.java:694: error: method getWidth in class Image cannot be applied to given types;
     g2d.drawImage( displayStartText, (int)((bgDispWidth-displayStartText.getWidth())/2), (int)((bgDispHeight-displayStartText.getHeight())/2), null );
                                                                         ^
  required: ImageObserver
  found: no arguments
  reason: actual and formal argument lists differ in length

关于为什么我可能会遇到这个问题的任何见解?


解决方案


Image没有getWidth()方法,如果你看一下JavaDocs你会发现它需要一个参数ImageObserver,因为当你请求值时图像可能没有加载(因为它的工作方式),你可以使用一个ImageObserver是当数据可用时通知。

所有 Swing 组件都实现了 ,因此如果该类是基于 Swing 的对象或者您没有ImageObserver,您可以(理论上)使用。thisnull

如果您正在使用null,那么您应该确保首先加载图像,例如使用MediaTracker否则可能getWidth(ImageObsever)会返回-1

更好的解决方案(恕我直言)是使用ImageIO.readwhich 将返回一个BufferedImagewhich is gurenteed to be loaded when it returns 并为您节省一些这些问题。

查看阅读/加载图像以获取更多详细信息



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.javaheidong.com/blog/article/583881/44555ce6efac3c5c875e/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

4 0
收藏该文
已收藏

评论内容:(最多支持255个字符)