【问题标题】:Java Applet Image LoadJava 小程序图像加载
【发布时间】:2013-07-26 06:52:38
【问题描述】:

我想在我的小程序中显示一个图像图标。我创建了一个包资源并将我的图像保存在其中。这就是我尝试的:-

Image logo;//I declare globally
logo = getImage("logo.jpg");//I initialize in the constructor

我使用这个程序

 public Image getImage(String name){
                URL imgUrl = getClass().getClassLoader().getResource("resources/"+name);
                ImageIcon icon = new ImageIcon(imgUrl);
                return icon.getImage();
            }

 public void paint(Graphics g)
        {
             if (logo!=null){
                    g.drawImage(logo, 30, 30, null);
                }
             g.drawString("Hwllo", 12, 12);
        }

然后我调用:

repaint() //In the Constructor

但我没有看到图像或我的字符串。可能是什么问题。此外,有没有更简单的方法可以在 Applet 中加载图像??

【问题讨论】:

  • 我认为SSCCE 会更有用
  • SSCCE 有帮助!!基本上图像正在加载,但我有一堆面板隐藏它
  • 这是我们建议避免覆盖顶级容器的paint(或通常为paint)的原因之一

标签: java applet awt paint imageicon


【解决方案1】:

您将 URL 设置为

URL imgUrl = getClass().getClassLoader().getResource("resources/"+name);
ImageIcon icon = new ImageIcon(imgUrl);

但是在调用paint方法时,你调用的是logo变量

 g.drawImage(logo, 30, 30, this);

问题出在您的设置 URL 值中,将 URL 设置为您的徽标变量,例如

URL url = new URL(/*Your resources herre*/, /*Your file name here*/);
logo=getImage(url);

之后使用paint方法显示图像。

【讨论】:

  • 这不是问题。有几种方法可以做同样的事情。
  • 您只需为变量设置有效的 url。然后将其传递给 logo 变量。你能明白我的意思吗?
  • 请将g.drawImage(logo, 30, 30, null); 更改为g.drawImage(logo, 30, 30, this);,以便我投票! Applet 实现了ImageObserver,因此我们可以避免使用MediaTracker
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-03
  • 1970-01-01
  • 2014-02-09
  • 2012-10-02
  • 2012-12-02
  • 2013-08-31
  • 1970-01-01
相关资源
最近更新 更多