无法使用AWT SystemTray

时间:2017-03-22 08:13:25

标签: java awt

import java.awt.*;

public class TrayIconDemo {

    public static void main(String[] args) throws AWTException, java.net.MalformedURLException {
        if (SystemTray.isSupported()) {
            TrayIconDemo td = new TrayIconDemo();
            td.displayTray();
        } else {
            System.err.println("System tray not supported!");
        }
    }

    public void displayTray() throws AWTException, java.net.MalformedURLException {
        //Obtain only one instance of the SystemTray object
        SystemTray tray = SystemTray.getSystemTray();

        //If the icon is a file
        Image image = Toolkit.getToolkit().createImage("icon.png");
        //Alternative (if the icon is on the classpath):
        //Image image = Toolkit.getToolkit().createImage(getClass().getResource("icon.png"));
        TrayIcon trayIcon = new TrayIcon(image, "Tray Demo");
        //Let the system resizes the image if needed
        trayIcon.setImageAutoSize(true);
        //Set tooltip text for the tray icon
        trayIcon.setToolTip("System tray icon demo");
        tray.add(trayIcon);
        trayIcon.displayMessage("Hello, World", "notification demo", TrayIcon.MessageType.INFO);
    }
}

当我将鼠标悬停在SystemTray或TrayIcon上时,我收到以下消息:

Usage of API documented as @since 1.6+ less... (Ctrl+F1) 
This inspection finds all usages of methods that have @since tag in their documentation.  This may be useful when development is performed under newer SDK version as the target platform for production.

这些课程带有红色下划线。我使用的是Windows 7 Enterprise,64位,SP1。可能是什么问题?

1 个答案:

答案 0 :(得分:0)

您的代码没有什么问题,但是您在IDE中的项目配置有问题。

  1. 确保您的构建工具使用的Java版本正确。对于系统托盘,至少需要Java 1.6。某些构建工具仍然默认使用相当旧的Java版本,例如,Maven默认使用1.5。因此,请确保在构建工具中选择了足够新的Java版本。
  2. 确保您的IDE与构建工具具有相同的设置。如果您的IDE支持您的构建工具,请从构建工具重新导入配置。如果没有,请手动设置配置。

在问题的评论中,您已经写到您正在使用IntelliJ IDEA。在IntelliJ IDEA中,您可以通过以下方式检查设置:

  1. 转到文件->项目结构。
  2. 在“项目设置”->“项目”中,确保Project SDK和项目语言级别足够新,至少为1.6。
  3. 在“项目设置->模块,依赖项”中,确保Module SDK足够新。

希望有帮助。

相关问题