【问题标题】:Getting an image to show up in Java获取要在 Java 中显示的图像
【发布时间】: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


【解决方案1】:

为什么要创建自定义组件?如果您创建自定义组件,那么您还需要覆盖组件的getPreferredSize() 方法以返回图像的大小,以便布局管理器可以以适当的大小绘制组件。

所以组件的大小可能是零,所以没有什么可以画的。

最简单的解决方案是使用JLabelImageIcon,让布局管理器处理大小问题。

【讨论】:

  • 每个人都这样做为什么不知道为什么:)
  • 我尝试使用它,但由于某种原因它仍然没有显示: JLabel iconLabel = new JLabel(new ImageIcon("background.png")); frame.add(iconLabel);
  • @user2963365,发布您的SSCCE,展示您如何使用 JLabel。确保在使框架可见之前将标签添加到框架。
猜你喜欢
  • 2013-06-19
  • 2014-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 2012-06-03
  • 2012-01-27
相关资源
最近更新 更多