Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java小程序图像加载_Java_Applet_Awt_Paint_Imageicon - Fatal编程技术网

Java小程序图像加载

Java小程序图像加载,java,applet,awt,paint,imageicon,Java,Applet,Awt,Paint,Imageicon,我想在我的小程序中显示一个图像图标。我创建了一个包resources,并在其中保存了我的图像。这是我尝试的:- Image logo;//I declare globally logo = getImage("logo.jpg");//I initialize in the constructor 我使用这个过程 Image logo;//I declare globally logo = getImage("logo.jpg");//I initialize in the construct

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

Image logo;//I declare globally
logo = getImage("logo.jpg");//I initialize in the constructor
我使用这个过程

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);
        }
然后我称之为:

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

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

您将URL设置为

Image logo;//I declare globally
logo = getImage("logo.jpg");//I initialize in the constructor
URL imgUrl = getClass().getClassLoader().getResource("resources/"+name);
ImageIcon icon = new ImageIcon(imgUrl);
但是在调用paint方法时,您正在调用logo变量

Image logo;//I declare globally
logo = getImage("logo.jpg");//I initialize in the constructor
 g.drawImage(logo, 30, 30, this);
问题在于设置URL值时,将URL设置为徽标变量,如

Image logo;//I declare globally
logo = getImage("logo.jpg");//I initialize in the constructor
URL url = new URL(/*Your resources herre*/, /*Your file name here*/);
logo=getImage(url);

之后,使用绘画方法显示图像。

我认为SSCCE帮助下,a将更有用!!基本上,图像正在加载,但我有一堆面板隐藏了它。这是我们建议避免覆盖顶级容器的
paint
(或者通常是
paint
)的原因之一。这不是问题。有几种方法可以做同样的事情。您只需为变量设置有效的url。然后将其传递给logo变量。你能理解我的观点吗?请更改
g.drawImage(logo,30,30,null)
g.drawImage(logo,30,30,this)这样我就可以投票了
Applet实现了
ImageObserver
,因此我们可以避免使用
MediaTracker
Image logo;//I declare globally
logo = getImage("logo.jpg");//I initialize in the constructor