【问题标题】:Getting icon package path in String java在String java中获取图标包路径
【发布时间】:2012-12-19 07:50:55
【问题描述】:

我有一个项目,其中我为图标制作了包..例如 com.example.icon 和 com.example.classes....现在我想设置一个字符串路径变量来设置这样的路径 .../ src/com/example/ui,然后我用它指定图标名称并访问图标..问题是我想动态设置它,以便我的 jar 文件在不同的系统中不会有问题..如何设置路径变量我无法弄清楚..谢谢

我见过File.getResource("some file name"),但我不想在开始时设置任何文件名.. 我正在使用网豆

编辑

现在我正在使用此代码..

  URL url = Main.class.getResource("PATH"); 
  String path = url.toString();
  .......
  ImageIcon icon = new ImageIcon(path+"/add_icon.png");

但它没有显示图标并显示“sun.tools.jar.main”的 Depericated Api 错误,我检查了系统路径值它是有效的.. ....?

【问题讨论】:

  • 试试String path = "/com/example/ui"; ImageIcon icon = new ImageIcon(this.getClass().getResource(path+"/add_icon.png"));

标签: java swing resources icons embedded-resource


【解决方案1】:

尝试使用

getClass().getResource("com/example/ui/imageFile");

【讨论】:

  • URL url = Main.Class.getClass().getResource("/com/idoccsmain/icons/");字符串路径 = rul.toString(); ...... ImageIcon icon = new ImageIcon(path+"/add_icon.png");我正在这样使用它,但它向我展示了一些已弃用的 api“sun.tools.jar.main”,并且我的图标尚未加载..
  • 每张图片都应该加载为 ImageIcon icon = new ImageIcon(Main.Class.getClass().getResource("/com/idoccsmain/icons/"+"add_icon.png");
  • 现在我正在尝试您提到的...当我通过 IDE 运行它时,它正在获取图标...但是当我在制作 jar 文件后运行它时它没有显示文件...?
【解决方案2】:

有多种方法可以做到这一点。要么使用命令行参数

public static void main(String[] args) {
    String path = args[0];
}

或属性

Properties props = new Properties();
props.load("Some Properties file in a fixed location");

String path = props.getProperty("path");

或系统属性(使用 -Dpath 选项调用)

String path = System.getProperty("path");

【讨论】:

    【解决方案3】:

    另外,您可以使用 ClassLoader 来获取 InputStream 并读取文件。

     fis = YourClass.class.getClassLoader().getResourceAsStream(FILE);
    

    【讨论】:

      【解决方案4】:

      如果您使用的是 NetBeans IDE,那么您可以使用 "jXImagePanel" 来显示图像,将图像设置为 jXImagePanel 的代码是:

      jXImagePanel2.setImage(getImage("icons/yourimage.jpg"));

      【讨论】:

      • 这不是问题……但我的问题是要找到“图标包”的路径。
      猜你喜欢
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 2015-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-13
      • 2016-01-11
      相关资源
      最近更新 更多