Anders Lassen
Anders Lassen

Reputation: 649

Making a java program run in the background of the computer

I've looked on some other posts about this, but didn't really understand much from it.

I've made a program that works like a server while capturing different pictures of the screen. Now, i'd like the program to just be active in the background - like the programs that appear under hidden icons. Programs that are not directly shown at the bottom taskbar. Do i need to add some specific code inside my java program when i execute it to a jar file? Or do i need to create the project some other way?

enter image description here

enter image description here

I hope this was enough explanation - Thanks in advance

Upvotes: 5

Views: 7800

Answers (3)

davidxxx
davidxxx

Reputation: 131326

SystemTray.getSystemTray().add(trayIcon) does the job.

Here an example of one of my application :

Image imageTrayIcon = Toolkit.getDefaultToolkit().createImage(YourClass.class.getResource("trayicon.png"));
    final TrayIcon trayIcon = new TrayIcon(imageTrayIcon, "title");

   // optional : a listener
    trayIcon.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {

        if (e.getClickCount() == 2 && !e.isConsumed()) {
            e.consume();
           // process  double click
           }
        }
    });
    // optional : adding a popup menu for the icon
    trayIcon.setPopupMenu(popup);

    // mandatory
    try {
        SystemTray.getSystemTray().add(trayIcon);
    }
    catch (AWTException e1) {
        // process the exception
    }

Upvotes: 0

cunniemm
cunniemm

Reputation: 689

Something super simple that I got from Here. All I did was add an exit on click.

Code

public static void main (String [] args) {
    if (!SystemTray.isSupported()) {
        System.out.println("SystemTray is not supported");
        return;
    }
    Image image = Toolkit.getDefaultToolkit().getImage("MY/PATH/TO_IMAGE");

    final PopupMenu popup = new PopupMenu();
    final TrayIcon trayIcon = new TrayIcon(image, "MY PROGRAM NAME", popup);
    final SystemTray tray = SystemTray.getSystemTray();

    MenuItem exitItem = new MenuItem("Exit");
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(1);
        }
    });
    popup.add(exitItem);

    trayIcon.setPopupMenu(popup);

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

Just get any image and add it to your resources or wherever you keep your images and make a path to it.

Upvotes: 3

anacron
anacron

Reputation: 6711

You can achieve this by using the java.awt.SystemTray API in combination with Java Swing API.

Refer this documentation from Oracle:

Oracle Java documentation for System Tray API

Upvotes: 1

Related Questions