无法将图像添加到JFrame?

时间:2014-01-17 15:32:21

标签: java swing jframe jlayeredpane

我有一个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));

enter image description here

如果iPath = C://Mobile.png图片显示。但是如果我提供iPath = "RemoteItServer/Mobile.png"iPath = "/RemoteItServer/res/images/Mobile.png"。它没有显示图片。

所以帮助我正确的方向:)

感谢您的帮助......

3 个答案:

答案 0 :(得分:1)

以下路径应该有效:

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

编辑:

也许您忘了将窗格添加到框架中。

getContentPane().add(layeredPane);

答案 1 :(得分:1)

路径可能很棘手。如果相对路径(例如Joschua提供的路径)不起作用,您可以将绝对路径拼凑在一起:

  

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

然后只连接到workingDir的相对路径:

  

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

另一种方法是使用File类,如下所示:

  

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

希望这有帮助。

答案 2 :(得分:0)

将图像直接放在您正在处理的项目中可以提供很多帮助。这样你只需要打电话给" Mobile.png"而不必担心这条路。

相关问题