我使用swingtrayicon时为什么不弹出窗口

xesrikrc  于 2021-07-08  发布在  Java
关注(0)|答案(0)|浏览(207)

我有一个问题,窗口不能弹出窗口,其中设置了定时器。方块下面的代码。我怎样才能解决这个问题?有人能告诉我吗。我非常感激。
我想把我的财富展示在弹出的窗口上。
当我第一次尝试这段代码时,它似乎成功了,但只有一次。我从未更改过代码,但它不起作用。
我试图重新启动我的电脑,我有两次,但也失败了。
我的电脑是Windows10x64系统

package systemTray;

import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.List;

import javax.swing.*;
import javax.swing.Timer;

/**
 * This program demonstrates the system tray API.
 * @version 1.02 2016-05-10
 * @author Cay Horstmann
 */
public class SystemTrayTest
{
   public static void main(String[] args)
   {
      SystemTrayApp app = new SystemTrayApp();
      app.init();
   }
}

class SystemTrayApp
{
   public void init()
   {      
      final TrayIcon trayIcon;

      if (!SystemTray.isSupported())
      {
         System.err.println("System tray is not supported.");
         return;
      }

      SystemTray tray = SystemTray.getSystemTray();
      Image image = new ImageIcon(getClass().getResource("cookie.png")).getImage();

      PopupMenu popup = new PopupMenu();
      MenuItem exitItem = new MenuItem("Exit");
      exitItem.addActionListener(event -> System.exit(0));
      popup.add(exitItem);

      trayIcon = new TrayIcon(image, "Your Fortune", popup);

      trayIcon.setImageAutoSize(true);
      trayIcon.addActionListener(event ->
         {
            trayIcon.displayMessage("How do I turn this off?",
                  "Right-click on the fortune cookie and select Exit.",
                  TrayIcon.MessageType.INFO);
         });

      try
      {
         tray.add(trayIcon);
      }
      catch (AWTException e)
      {
         System.err.println("TrayIcon could not be added.");
         return;
      }
      //get fortunes to show 
      final List<String> fortunes = readFortunes();
      // I want to pop up window to show message with the timer.
      Timer timer = new Timer(10000, event ->
         {
            int index = (int) (fortunes.size() * Math.random());
            trayIcon.displayMessage("Your Fortune", fortunes.get(index),
                  TrayIcon.MessageType.INFO);
         });
      timer.start();
   }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题