简体   繁体   English

无法将图像添加到JFrame?

[英]Can't add Images to JFrame?

I Have a JFrame.I can't add images to it.I don't know how to give the Correct Image path. 我有一个JFrame.I无法添加图像。我不知道如何给出正确的图像路径。

  String iPath = "RemoteItServer/Mobile.png";
                JLayeredPane layeredPane = new JLayeredPane();
                layeredPane.setBounds(0, 0, 315, 610);

                JLabel mobileImageLabel = new JLabel(new ImageIcon(iPath));
                mobileImageLabel.setBounds(0, 0, 315, 610);
                layeredPane.add(mobileImageLabel, Integer.valueOf(0));

在此输入图像描述

If iPath = C://Mobile.png the image is Shown.But if i give iPath = "RemoteItServer/Mobile.png" or iPath = "/RemoteItServer/res/images/Mobile.png" .It is not showing the Image. 如果iPath = C://Mobile.png图像是Shown.But,如果我给iPath = "RemoteItServer/Mobile.png"iPath = "/RemoteItServer/res/images/Mobile.png" iPath = "RemoteItServer/Mobile.png" iPath = "/RemoteItServer/res/images/Mobile.png"它没有显示图像。

So Help me in the Right Direction :) 所以帮助我正确的方向:)

Thanks for your Help ... 谢谢你的帮助 ...

The following path should work: 以下路径应该有效:

String iPath = "res/images/Mobile.png";

Edit: 编辑:

And maybe you forgot to add the pane to the Frame. 也许你忘了将窗格添加到Frame。

getContentPane().add(layeredPane);

Paths can be tricky. 路径可能很棘手。 If a relative path, such as the one provided by Joschua, doesn't work, you can piece together an absolute path like so: 如果相对路径(例如Joschua提供的路径)不起作用,则可以将绝对路径拼凑在一起,如下所示:

String workingDir = System.getProperty("user.dir"); String workingDir = System.getProperty(“user.dir”);
String separator = System.getProperty("file.separator"); String separator = System.getProperty(“file.separator”);

Then just concatenate the relative path to the workingDir: 然后只连接到workingDir的相对路径:

workingDir + separator + "res/images/Mobile.png"; workingDir + separator +“res / images / Mobile.png”;

Another way to do this is to use the File class like so: 另一种方法是使用File类,如下所示:

File file = new File("res/images/Mobile.png"); 文件文件=新文件(“res / images / Mobile.png”);
String path = file.getAbsolutePath(); String path = file.getAbsolutePath();

Hope this helps. 希望这可以帮助。

What can help a lot is to put the image directly in the project you are working on. 可以帮助很多的是将图像直接放在您正在处理的项目中。 This way you will only have to call "Mobile.png" and not have to worry about the path. 这样你只需要调用“Mobile.png”而不必担心路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM