tags:

views:

264

answers:

1

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);
    }

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.

+1  A: 

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.

Peter Lang
How can I start accepting answers on StackOverflow?
Chan Pye
You can up- and downvote (arrows left) good/helpful and bad/wrong answers. For accepting see http://meta.stackoverflow.com/questions/5234/accepting-answers-what-is-it-all-about/5235#5235. You can both upvote and accept an answer.
Peter Lang