如何在java中动态地将MenuItem添加到TrayIcon的菜单中?

时间:2013-06-13 15:08:40

标签: java swing jmenuitem jpopupmenu trayicon

我有一个ChatServer应用程序,当ChatServer启动时,TrayIcon将显示在系统托盘中,当我右键单击该Trayicon时,有一个名为who is online的菜单,我想在客户端连接时将MenuItem添加到此菜单聊天服务器,问题是如何动态添加MenuItem?我用过  onlineMenu.add(next);

我的TrayIcon类如下(不是整个代码)

public class TrayIconDemo {
     private TrayIcon trayIcon ;
     private Menu onlineMenu = new Menu("Who's Online(?)");

     public void startUp() {
    /* Use an appropriate Look and Feel */
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        //UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    } catch (UnsupportedLookAndFeelException ex) {
        ex.printStackTrace();
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
    } catch (InstantiationException ex) {
        ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    }
    /* Turn off metal's use of bold fonts */
    UIManager.put("swing.boldMetal", Boolean.FALSE);
    //Schedule a job for the event-dispatching thread:
    //adding TrayIcon.
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}


private void createAndShowGUI() {
    //Check the SystemTray support
    if (!SystemTray.isSupported()) {
        System.out.println("SystemTray is not supported");
        return;
    }
    final PopupMenu popup = new PopupMenu();
    trayIcon = new TrayIcon(createImage("images/bulb.gif", "tray icon"));
    final SystemTray tray = SystemTray.getSystemTray();

    // Create a popup menu components
    MenuItem aboutItem = new MenuItem("About");
    //CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
    //CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");

   // MenuItem errorItem = new MenuItem("Error");
   // MenuItem warningItem = new MenuItem("Warning");
    MenuItem infoItem = new MenuItem("Info");
   // MenuItem noneItem = new MenuItem("None");
    MenuItem exitItem = new MenuItem("Exit");

    //Add components to popup menu
    popup.add(aboutItem);
    popup.addSeparator();
   // popup.add(cb1);
   // popup.add(cb2);
    popup.addSeparator();
    popup.add(onlineMenu);
    //onlineMenu.add("Hi...");
    //displayMenu.add(errorItem);
    //displayMenu.add(warningItem);
    //displayMenu.add(infoItem);
    //displayMenu.add(noneItem);
    popup.add(exitItem);

    trayIcon.setPopupMenu(popup);
    trayIcon.setImageAutoSize(true);
    trayIcon.setToolTip("Chat Server "+serverIpAddress+"");


    try {
        tray.add(trayIcon);
    } catch (AWTException e) {
        System.out.println("TrayIcon could not be added.");
        return;
    }
    //Default Tray notification
    trayIcon.displayMessage("Server", "Server Started! server IP is "+serverIpAddress+"",
        TrayIcon.MessageType.NONE);
    trayIcon.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null,
                    "Chat Server Started and Running succesfully.");
        }
    });

    aboutItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null,
                    "Chat server version 1.01.Developed by Roshan.");
        }
    });

   /* cb1.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            int cb1Id = e.getStateChange();
            if (cb1Id == ItemEvent.SELECTED){
                trayIcon.setImageAutoSize(true);
            } else {
                trayIcon.setImageAutoSize(false);
            }
        }
    });*/

    /*cb2.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            int cb2Id = e.getStateChange();
            if (cb2Id == ItemEvent.SELECTED){
                trayIcon.setToolTip("Chat Server");
            } else {
                trayIcon.setToolTip(null);
            }
        }
    });*/

    ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            MenuItem item = (MenuItem)e.getSource();
            //TrayIcon.MessageType type = null;
            System.out.println(item.getLabel());
            if ("Error".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.ERROR;
                trayIcon.displayMessage("Chat Server",
                        "This is an error message", TrayIcon.MessageType.ERROR);

            } else if ("Warning".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.WARNING;
                trayIcon.displayMessage("Sun TrayIcon Demo",
                        "This is a warning message", TrayIcon.MessageType.WARNING);

            } else if ("Info".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.INFO;
                trayIcon.displayMessage("Sun TrayIcon Demo",
                        "This is an info message", TrayIcon.MessageType.INFO);

            } else if ("None".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.NONE;
                trayIcon.displayMessage("Sun TrayIcon Demo",
                        "This is an ordinary message", TrayIcon.MessageType.NONE);
            }
        }
    };

    //errorItem.addActionListener(listener);
    //warningItem.addActionListener(listener);
    infoItem.addActionListener(listener);
    //noneItem.addActionListener(listener);


    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            tray.remove(trayIcon);
            System.exit(0);
        }
    });
}

现在我想在onlineMenu中添加一个menuItem 当客户端连接到服务器时,此方法将调用

public void setClientIpName(String ipNameClient){//receiving ipNameClient veriable inside ip+com_name
  String[] token =ipNameClient.split("/"); //token[1]=ip , token[2]=computer name
  this.addClient(token[2]);//send name nad return treeset 
  if(!clients.isEmpty()){
    JOptionPane.showMessageDialog(null,clients.size()+"");
    Iterator iterator;
    iterator = clients.iterator(); 
    while (iterator.hasNext()){
    String next = iterator.next()+"";
         onlineMenu.add(next);
      }
}
}

但它想要将任何MenuItem添加到onlineMenu,任何人都可以提供帮助吗?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您想要在将其附加到Trayicon后修改弹出菜单吗?我相信不支持

您有两种选择:

a。)构建一个全新的PopupMenu并用新的菜单替换TrayIcon的当前菜单。

b。)根本不要将任何PopupMenu附加到TrayIcon - 而是在MouseEvent指示isPopupTrigger()== true时附加MouseListener并创建菜单。然后,您可以打开一个普通的Swing弹出菜单(如果您没有打开窗口,这可能会变得棘手)。