开发者

How to Use context menu with tray icon in Java?

I'm using Netbeans to develop a Java application and I want to create a tray icon at system tray and a popup menu will be display when I right click on tray icon.

I have created a jframe and popup menu by drop and drap them.

But I have a problem.My popup menu have 2 menu items (Exit and Show Login) but selected menu item is not high-lighted and after I click menu item, popup menu is not closed.

Here is my code:

Declare some global variables

SystemTray systemTray = null;
Image image = Toolkit.getDefaultToolkit().getImage("D:/key-16x16.png");

TrayIcon trayIcon = new TrayIcon(image);

Create and display system tray icon

 systemTray = SystemTray.getSystemTray();
    try
    {
        systemTray.add(trayIcon);
    } catch (AWTException ex)
    {
        Logger.getLogger(mainframe.class.getName()).log(Level.SEVERE, null, ex);
   开发者_JAVA百科 }

Create MouseAdapter and add mouseListener for tray icon

MouseAdapter trayIconMouseAdapter = new MouseAdapter()
    {
      //  @Override
       public void mouseClicked(MouseEvent e) {
                trayIconMouseClicked(e);
       }
    };

   trayIcon.addMouseListener(trayIconMouseAdapter);

handle mouse click event on tray icon. Check whether it is a right click and show popupmenu

private void trayIconMouseClicked(java.awt.event.MouseEvent evt) {

    if(SwingUtilities.isRightMouseButton(evt))
    {
      popupMeunu.show(evt.getComponent(), evt.getX(), evt.getY());

    }
}

But if i drap a button to jframe and replace popupMeunu.show(evt.getComponent(), evt.getX(), evt.getY()); by popupMeunu.show(jButton1, evt.getX(), evt.getY()); everything will be OK.

I don't know why?Pls help me to slove my problem.


Don't add your own MouseListener.

Pass your popupMeunu (which needs to be a java.awt.PopupMenu, not javax.swing.JPopupMenu) in the constructor of TrayIcon like that:

TrayIcon trayIcon = new TrayIcon(image, "The Tip Text", popup);

I copied this from this tutorial and it worked fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜