Jump to content

System Tray class


Septron
 Share

Recommended Posts

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionListener;

public class Tray {
    
    private PopupMenu popup;
    private final TrayIcon tray;
    
    private final String scriptName;
    private boolean showing = false;
    
    public Tray(Image image, String scriptName) {
        this.tray = new TrayIcon(image, scriptName);
        this.scriptName = scriptName;
    }
    
    public void show() throws AWTException {
        if (SystemTray.isSupported()) {
            if (this.tray != null) {
                this.tray.setToolTip(this.scriptName);
                this.tray.setImageAutoSize(true);
                SystemTray.getSystemTray().add(this.tray);
                this.showing = true;
            }
        } else {
            throw new AWTException("System Tray is not supported!");
        }
    }
    
    public void hide() {
        if(this.showing == true && this.tray != null) {
            SystemTray.getSystemTray().remove(tray);
            this.showing = false;
        }
    }
    
    public void addMenuItem(MenuItem item, ActionListener listener) {
        item.addActionListener(listener);
        this.popup.add(item);
        if(this.tray != null)
            this.tray.setPopupMenu(popup);
    }
    
    public void sendDisplayMessage(String message, TrayIcon.MessageType type) {
        if(this.showing == true)
            this.tray.displayMessage(this.scriptName, message, type);
    }
}

Example usage...

        final Tray tray = new Tray(ImageIO.read(new URL("http://i.imgur.com/HGN98TQ.gif")), "Cool Script");
        tray.addMenuItem(new MenuItem("Hide"), new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                tray.hide();
            }
        });
        tray.show();
        tray.sendDisplayMessage("Cool Script initalized!", TrayIcon.MessageType.INFO);
  • Like 2
Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...