1

所以我正在尝试使用托盘菜单并且我有这条线。

final TrayIcon trayIcon = new TrayIcon(createImage("duke.jpg", "tray icon"));

方法 createImage 是

protected static Image createImage(String path, String description) {
    URL imageURL = TrayIconDemo.class.getResource(path);

    if (imageURL == null) {
        System.err.println("Resource not found: " + path);
        return null;
    } else {
        return (new ImageIcon(imageURL, description)).getImage();
    }
}

当我运行程序时出现以下错误

Resource not found: duke.jpg
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: creating TrayIcon with null Image
    at java.awt.TrayIcon.<init>(Unknown Source)
    at misc.TrayIconDemo.createAndShowGUI(TrayIconDemo.java:76)
    at misc.TrayIconDemo.access$0(TrayIconDemo.java:68)
    at misc.TrayIconDemo$1.run(TrayIconDemo.java:63)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

这是我的文件夹的图片,显示了图像的位置。

http://i.stack.imgur.com/80tFY.png

我只想声明,我发现了这个http://www.oracle.com/technetwork/articles/javase/systemtray-139788.html,无论有没有图像,它都能正常工作。此外,图像必须放在源文件夹中,而不是 .java 所在的文件夹中才能显示,所以我假设它必须存在于我的问题所涉及的原始代码中。因此,如果有人需要有关系统托盘的帮助,只需检查链接。

4

2 回答 2

0

您可以做的最简单的方法是System.out.println(new File(".").getAbsolutePath())找出被视为根路径的路径,然后调整文件的实际路径。

我使用它是因为 webapp(基于 Servlet)和 Java SE 应用程序之间存在差异。

于 2013-06-25T19:43:37.847 回答
0

如果您像这样更改此方法,它会起作用。

protected static Image createImage() {
            String path="bulb.gif";
            String description="";
            String imageURL = path;
            if (imageURL == null) {
                System.err.println("Resource not found: " + path);
                return null;
            } else {
                return (new ImageIcon(imageURL, description)).getImage();
            }
        }
于 2014-02-19T15:41:29.247 回答