gpt4 book ai didi

java - 无法在图像上调用 getWidth()

转载 作者:行者123 更新时间:2023-11-30 02:57:03 26 4
gpt4 key购买 nike

我有一个图像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 组件都实现 ImageObserver,因此(理论上)如果该类是基于 Swing 的对象,则可以使用 this;如果您是基于 Swing 的对象,则可以使用 null没有。

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

更好的解决方案(恕我直言)是使用 ImageIO.read ,它将返回一个 BufferedImage ,保证在返回时加载它并为您保存其中的一些问题。

看看Reading/Loading an image了解更多详情

关于java - 无法在图像上调用 getWidth(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36973852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com