Open popup(Menu) on task tray icon with left click using java
Asked Answered
S

5

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

    }
}
Spandau answered 11/7, 2012 at 7:54 Comment(3)
What do you have so far?Snowfield
@ Guillaume Polet, thank you for your great helpSpandau
You can up-vote and/or accept an answer if it helped and/or solved your issue. Cheers ;-)Snowfield
S
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);
Snowfield answered 12/7, 2012 at 12:15 Comment(7)
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)Spandau
@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.Snowfield
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 barSpandau
@Farid, not completely sure but you could use a JWindow insteadSnowfield
Great idea. i took much help from your answer.Ellipsoid
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 https://mcmap.net/q/591218/-show-jframe-but-not-show-title-bar-on-task-bar. So just setType with UTILITY and you are good to go.Michikomichon
@Michikomichon duely noted. I updated the post to reflect that. Thanks and cheersSnowfield
H
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");
   }
});
Hahn answered 11/7, 2012 at 8:7 Comment(2)
@Farid doesn't matter, if popup menu, popup window or dialogHahn
I haven't any issue with your code, JPopupMenu accelerator for setPopupMenu() is right mouse button, use show(Component invoker, int x, int y)Hahn
O
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.

Outrush answered 11/7, 2012 at 8:6 Comment(1)
The link you added is for c# not JavaSnowfield
O
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

Oncoming answered 11/7, 2012 at 8:7 Comment(1)
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 clickSpandau
T
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).

Thach answered 10/4, 2016 at 18:46 Comment(1)
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.Cantilena

© 2022 - 2024 — McMap. All rights reserved.