14

I am working on task tray Icon in java, I like to open a popup Menu using left click same popup Menu as I open on right click, and please help me with a quick response.

Thanks in advance...

here is the code working for right click need to show same popup on left click... don't forget to place any image @ "src/img" folder with name "titleImg.jpg"

Just run this... it is a working example but i have to show same popup using left click

i have checked the Mouse Listener, it listen the left click on tray icon but how to show popup menu using that ???

    package com.abc.dao;

import java.awt.AWTException;
import java.awt.CheckboxMenuItem;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;

public class MyTaskTray {
    public static void main(String arg[]){

        //Check the SystemTray is supported
        if (!SystemTray.isSupported()) {
            System.out.println("SystemTray is not supported");
            return;
        }
        final PopupMenu popup = new PopupMenu();
        final TrayIcon trayIcon =
                new TrayIcon(Toolkit.getDefaultToolkit().getImage(new java.io.File("").getAbsolutePath()+"/bin/img/titleImg.jpg"), "Library Drop");
        final SystemTray tray = SystemTray.getSystemTray();

        // Create a pop-up menu components
        MenuItem aboutItem = new MenuItem("About");
        CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
        CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
        Menu displayMenu = new Menu("Display");
        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 pop-up menu
        popup.add(aboutItem);
        popup.addSeparator();
        popup.add(cb1);
        popup.add(cb2);
        popup.addSeparator();
        popup.add(displayMenu);
        displayMenu.add(errorItem);
        displayMenu.add(warningItem);
        displayMenu.add(infoItem);
        displayMenu.add(noneItem);
        popup.add(exitItem);

        trayIcon.setPopupMenu(popup);

        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
        }

    }
}
NoNaMe
  • 6,020
  • 30
  • 82
  • 110

5 Answers5

15

What you actually lack is a parent component to show your PopupMenu. One way to achieve this, is to use an "invisible" frame (actually it is visible but with 0-bounds and undecorated, so you can't see it) like this:

import java.awt.AWTException;
import java.awt.CheckboxMenuItem;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.MalformedURLException;
import java.net.URL;

public class MyTaskTray {
    public static void main(String arg[]) throws MalformedURLException {
        final Frame frame = new Frame("");
        frame.setUndecorated(true);
        // Check the SystemTray is supported
        if (!SystemTray.isSupported()) {
            System.out.println("SystemTray is not supported");
            return;
        }
        final TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(
                new URL("http://home.comcast.net/~supportcd/Icons/Java_Required.jpg")), "Library Drop");
        final SystemTray tray = SystemTray.getSystemTray();

        // Create a pop-up menu components
        final PopupMenu popup = createPopupMenu();
        trayIcon.setPopupMenu(popup);
        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) {
                    frame.add(popup);
                    popup.show(frame, e.getXOnScreen(), e.getYOnScreen());
                }
            }
        });
        try {
            frame.setResizable(false);
            frame.setVisible(true);
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
        }

    }

    protected static PopupMenu createPopupMenu() {
        final PopupMenu popup = new PopupMenu();
        MenuItem aboutItem = new MenuItem("About");
        CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
        CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
        Menu displayMenu = new Menu("Display");
        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 pop-up menu
        popup.add(aboutItem);
        popup.addSeparator();
        popup.add(cb1);
        popup.add(cb2);
        popup.addSeparator();
        popup.add(displayMenu);
        displayMenu.add(errorItem);
        displayMenu.add(warningItem);
        displayMenu.add(infoItem);
        displayMenu.add(noneItem);
        popup.add(exitItem);
        return popup;
    }
}

As of Java 1.7, you can add the following line to remove the application bar from the taskbar:

frame.setType(Type.UTILITY);
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
  • it is working good but when i right click on the icon and after that when i left click on the icon, by clicking left if gives the Exception:java.lang.IllegalArgumentException: origin not in parent's hierarchy at java.awt.PopupMenu.show(Unknown Source) at com.MyTaskTray$1.mouseClicked(MyTaskTray.java:66) at java.awt.TrayIcon.processMouseEvent(Unknown Source) at java.awt.TrayIcon.processEvent(Unknown Source) at java.awt.TrayIcon.dispatchEvent(Unknown Source) – NoNaMe Jul 26 '12 at 06:59
  • @Farid indeed it causes issue, I missed that. THe solution is to add the popup to the `frame` right before showing the popup. I have updated my post to reflect that. – Guillaume Polet Jul 26 '12 at 12:53
  • this solved my issue and working good, but there is one thing that will be good for the user use it next time that if we use JDialog in place of Frame it will become more good as it will not show the Frame on the start bar – NoNaMe Jul 27 '12 at 05:07
  • 1
    @Farid, not completely sure but you could use a JWindow instead – Guillaume Polet Jul 27 '12 at 17:06
  • Great idea. i took much help from your answer. – Haseeb Wali Dec 09 '12 at 18:10
  • Keep in note that this solution using `Frame` would add title bar to the task menu. If you don't want it check following answer http://stackoverflow.com/a/19093753/445600. So just setType with UTILITY and you are good to go. – starcorn May 22 '16 at 11:34
  • @starcorn duely noted. I updated the post to reflect that. Thanks and cheers – Guillaume Polet May 23 '16 at 19:55
4

you can add ActionListener to the TrayIcon, mouse double_click can showing JOptionPane

trayIcon.addActionListener(new ActionListener() {

   @Override
   public void actionPerformed(ActionEvent e) {
       JOptionPane.showMessageDialog(null, "This dialog box is run from System Tray");
   }
});
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • @Farid doesn't matter, if popup menu, popup window or dialog – mKorbel Jul 12 '12 at 10:56
  • I haven't any issue with your code, JPopupMenu accelerator for `setPopupMenu()` is right mouse button, use [show(Component invoker, int x, int y)](http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html) – mKorbel Jul 12 '12 at 11:19
2

I think you are looking for a MouseListener which you will add to your TrayIcon and will activate when a button on the mouse is clicked,moved etc. To get it to operate for left clicks only have a look at the ButtonMasks on MouseEvent (BUTTON1) being for left mouse clicks.

David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
1

You could read the official tutorial at http://docs.oracle.com/javase/tutorial/uiswing/misc/systemtray.html or check out http://weblogs.java.net/blog/ixmal/archive/2006/05/using_jpopupmen.html for a solution to use a jpopuomenu instead

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • already checked this example, it has 2 issues, 1st it also works for right click not for left and 2nd when it shows popup menu that menu does not get removed... and the 1st example u gave works for right click only i also used this one for right click. but i have to show same popup on left click – NoNaMe Jul 12 '12 at 10:45
1

This should work:

trayIcon.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        JOptionPane.showMessageDialog(null, "This shows after a left-click on tray icon");
    }
});

Override any other methods if you want a different kind of event (not just the click event from the example above).

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
  • The question was "How to show the popup menu associated to the tray icon" and not "How to show a dialog". This does not answer the question. – ceving Mar 17 '23 at 11:27