【问题标题】:Can't add Images to JFrame?无法将图像添加到 JFrame?
【发布时间】:2014-01-17 15:32:20
【问题描述】:

我有一个 JFrame。我无法向其中添加图像。我不知道如何提供正确的图像路径。

  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));

如果iPath = C://Mobile.png 显示图像。但如果我给iPath = "RemoteItServer/Mobile.png"iPath = "/RemoteItServer/res/images/Mobile.png"。它不显示图像。

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

感谢您的帮助...

【问题讨论】:

    标签: java swing jframe jlayeredpane


    【解决方案1】:

    以下路径应该有效:

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

    编辑:

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

    getContentPane().add(layeredPane);
    

    【讨论】:

      【解决方案2】:

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

      String workingDir = System.getProperty("user.dir");
      字符串分隔符 = System.getProperty("file.separator");

      然后将相对路径连接到workingDir:

      workingDir + 分隔符 + "res/images/Mobile.png";

      另一种方法是像这样使用 File 类:

      文件 file = new File("res/images/Mobile.png");
      字符串路径 = file.getAbsolutePath();

      希望这会有所帮助。

      【讨论】:

        【解决方案3】:

        将图像直接放入您正在处理的项目中会很有帮助。这样,您只需调用“Mobile.png”,而不必担心路径。

        【讨论】:

          猜你喜欢
          • 2013-08-04
          • 1970-01-01
          • 2019-06-06
          • 2015-11-08
          • 1970-01-01
          • 2013-03-29
          • 2015-03-31
          • 2012-01-27
          相关资源
          最近更新 更多