How do I add an event to the TrayIcon notification balloon?

1

I have an application that uses the TrayIcon class and I'm displaying a message through the displayMessage() method. (A small "balloon" that rises from the icon represented by my TrayIcon).

The method call is as follows:

tray.displayMessage("My Title", "My Message", TrayIcon.MessageType.WARNING);

Where tray is my object of type TrayIcon .

But when I click on this "balloon" nothing happens. In fact, the "balloon" is closed. But I need to do something specific when this message is clicked. How do I add a mouse click event to this message?

If this is not possible, can someone suggest an alternative to solve my problem?

Here's a snippet of code:

import java.awt.AWTException;   
import java.awt.Image;    
import java.awt.SystemTray;  
import java.awt.Toolkit;  
import java.awt.TrayIcon;

public class Principal {

    Principal() {
        initialize();
    }

    private void initialize() {
        Image trayImage = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("icon.png"));
        TrayIcon tray = new TrayIcon(trayImage, "Tray Icon Example");
        SystemTray sysTray = SystemTray.getSystemTray();
        try {
            sysTray.add(tray);
        } catch (AWTException e) {
            e.printStackTrace();
        }
        tray.displayMessage("Atenção!", "Clique aqui para abrir mais detalhes.", TrayIcon.MessageType.WARNING);
    }

    public static void main(String[] args) {
        new Principal();
    }

}
    
asked by anonymous 04.08.2016 / 17:30

1 answer

3

Add a ActionListener to your TrayIcon :

tray.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //ação que vai ocorrer quando o balão
               //for clicado
            }
        });

See implemented in an executable example:

import java.awt.AWTException;   
import java.awt.Image;    
import java.awt.SystemTray;  
import java.awt.Toolkit;  
import java.awt.TrayIcon;

public class Principal {

    Principal() {
        initialize();
    }

    private void initialize() {
        Image trayImage = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("icon.png"));
        TrayIcon tray = new TrayIcon(trayImage, "Tray Icon Example");
        SystemTray sysTray = SystemTray.getSystemTray();
        tray.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "clicou");
            }
        });
        try {
            sysTray.add(tray);
        } catch (AWTException e) {
            e.printStackTrace();
        }
        tray.displayMessage("Atenção!", "Clique aqui para abrir mais detalhes.", TrayIcon.MessageType.WARNING);
    }

    public static void main(String[] args) {
        new Principal();
    }
}

See working:

    
04.08.2016 / 20:42