【发布时间】:2014-05-23 20:14:24
【问题描述】:
我正在尝试在 JFrame 中显示背景图像,但图像未显示,并且我找不到代码中的错误。
public class GraphicsComponent extends JComponent
{
int xPosition = 200;//initializes and declares the x coordinate
int yPosition = 400;//initializes and declares the y coordinate
Image i;
public GraphicsComponent()
{
try{
File sky = new File("lib/background.png");
i = ImageIO.read(sky);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void paintComponent(Graphics g) //overrides paintComponent method in JComponent
{
if (i == null) return;
g.drawImage(i, 0, 0, this);
}
【问题讨论】:
-
你的主程序里有什么..
-
能否贴出完整的代码。您如何将其添加到
JFrame? -
图片在哪里?它是位于 src/application 上下文中还是相对于程序的执行?是否抛出异常?您还应该调用 super.paintComponent,尤其是对于 JComponent,因为它默认是透明的
-
部署时,这些资源可能会变成embedded-resource。在这种情况下,资源必须由
URL而不是File访问。查看标签的info page,了解形成URL的方法。
标签: java image swing graphics javax.imageio