36

I'd created a JFrame and want to hide in taskbar (in windows not visible right in the bottom but hidden in the tray menu items).
Can anybody tell me how to do that?
Did I need to make some changes in System settings of windows?
for example, you might have seen some download managers, team viewer, 4shared desktop, etc. are hide in taskbar's tray menu items.

Mohammad Faisal
  • 5,241
  • 14
  • 63
  • 114

3 Answers3

52
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.UIManager;

/**
 *
 * @author Mohammad Faisal
 * ermohammadfaisal.blogspot.com
 * facebook.com/m.faisal6621
 *
 */

public class HideToSystemTray extends JFrame{
    TrayIcon trayIcon;
    SystemTray tray;
    HideToSystemTray(){
        super("SystemTray test");
        System.out.println("creating instance");
        try{
            System.out.println("setting look and feel");
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }catch(Exception e){
            System.out.println("Unable to set LookAndFeel");
        }
        if(SystemTray.isSupported()){
            System.out.println("system tray supported");
            tray=SystemTray.getSystemTray();

            Image image=Toolkit.getDefaultToolkit().getImage("/media/faisal/DukeImg/Duke256.png");
            ActionListener exitListener=new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Exiting....");
                    System.exit(0);
                }
            };
            PopupMenu popup=new PopupMenu();
            MenuItem defaultItem=new MenuItem("Exit");
            defaultItem.addActionListener(exitListener);
            popup.add(defaultItem);
            defaultItem=new MenuItem("Open");
            defaultItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    setVisible(true);
                    setExtendedState(JFrame.NORMAL);
                }
            });
            popup.add(defaultItem);
            trayIcon=new TrayIcon(image, "SystemTray Demo", popup);
            trayIcon.setImageAutoSize(true);
        }else{
            System.out.println("system tray not supported");
        }
        addWindowStateListener(new WindowStateListener() {
            public void windowStateChanged(WindowEvent e) {
                if(e.getNewState()==ICONIFIED){
                    try {
                        tray.add(trayIcon);
                        setVisible(false);
                        System.out.println("added to SystemTray");
                    } catch (AWTException ex) {
                        System.out.println("unable to add to tray");
                    }
                }
        if(e.getNewState()==7){
                    try{
            tray.add(trayIcon);
            setVisible(false);
            System.out.println("added to SystemTray");
            }catch(AWTException ex){
            System.out.println("unable to add to system tray");
        }
            }
        if(e.getNewState()==MAXIMIZED_BOTH){
                    tray.remove(trayIcon);
                    setVisible(true);
                    System.out.println("Tray icon removed");
                }
                if(e.getNewState()==NORMAL){
                    tray.remove(trayIcon);
                    setVisible(true);
                    System.out.println("Tray icon removed");
                }
            }
        });
        setIconImage(Toolkit.getDefaultToolkit().getImage("Duke256.png"));

        setVisible(true);
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String[] args){
        new HideToSystemTray();
    }
}

This is the working program!

Community
  • 1
  • 1
Mohammad Faisal
  • 5,241
  • 14
  • 63
  • 114
4

myFrame#getExtendedState and myFrame#setExtendedState

basically is better to multiplay these ExtendedStates

frame.setExtendedState(JFrame.ICONIFIED);
frame.setExtendedState(frame.getExtendedState() | JFrame.ICONIFIED);


frame.setExtendedState(JFrame.NORMAL);
frame.setExtendedState(frame.getExtendedState() & (~JFrame.ICONIFIED));

EDIT 1.

for example

import java.awt.event.ActionEvent;
import javax.swing.*;  
public class WindowGCDemo1 {  
    private javax.swing.Timer timer = null;
    private int count = 0;
    private JFrame myFrame = new JFrame();  
    public WindowGCDemo1() {
        myFrame = new JFrame();
        myFrame.setLocation(150, 150);
        myFrame.setSize(200, 400);
        myFrame.setVisible(true);
        System.out.println(myFrame.getExtendedState());
        start();
    }  
    private void start() {
        timer = new javax.swing.Timer(1000, updateCol());
        timer.start();
    }  
    public Action updateCol() {
        return new AbstractAction("Set Delay") {  
            private static final long serialVersionUID = 1L;  
            @Override
            public void actionPerformed(ActionEvent e) {
                timer.stop();
                myFrame.setExtendedState(JFrame.ICONIFIED);
                System.out.println(myFrame.getExtendedState());
                count++;
                startAgain();
            }
        };
    }  
    private void startAgain() {
        timer = new javax.swing.Timer(1000, updateColAgain());
        timer.start();
    }  
    public Action updateColAgain() {
        return new AbstractAction("Set Delay") {  
            private static final long serialVersionUID = 1L;  
            @Override
            public void actionPerformed(ActionEvent e) {
                timer.stop();
                myFrame.setExtendedState(JFrame.NORMAL);
                System.out.println(myFrame.getExtendedState());
                count++;
                if (count > 5) {
                    timer.stop();
                    stop();
                }
                start();
            }
        };
    }  
    private void stop() {
        System.out.println("--------------------------------------------");
        System.out.println("System Exit");
        System.exit(0);
    } 
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {  
            @Override
            public void run() {
                WindowGCDemo1 windowGCDemo = new WindowGCDemo1();
            }
        });
    }
}

EDIT 2.

for SystemTry you have to set for your JFrame#setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); and in the proper JMenuItem(s) from JPopupMenu, just JFrame#setVisible(true);

mKorbel
  • 108,320
  • 17
  • 126
  • 296
  • I didn't get it correctly. Please tell me the steps to be followed! – Mohammad Faisal Sep 18 '11 at 12:55
  • The above method seems to be for `setting` and `getting` the frame's extended state but what about the logic to be implemented for minimizing the `frame` to the system tray icon? – Mohammad Faisal Sep 18 '11 at 13:23
  • hmmm I can't read whole question see my EDIT 1 for my missunderstood – mKorbel Sep 18 '11 at 13:40
  • will be added answer to your question, my bad – mKorbel Sep 18 '11 at 13:41
  • It is best to link to the latest version of the JavaDocs. I have edited your answer to point to J2SE 7. For tips on getting a link to the latest docs, see [point 2 of advantages](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7090875). – Andrew Thompson Sep 18 '11 at 13:58
  • @Andrew: why u had deleted the Edit 2? – Mohammad Faisal Sep 18 '11 at 14:13
  • Deleted? I thought your edit went through and then I further edited the post. Feel free to reinstate it (just remember to change the '6' to '7' in the links). – Andrew Thompson Sep 18 '11 at 14:20
  • @Andrew: I'm not understanding how the Edit 2 is deleted. I just removed the spaces and extra lines. Can u revise the post again? Please!!! – Mohammad Faisal Sep 18 '11 at 14:22
  • @mKorbel: The above code just making the frame to show and hide(iconified) feature but I'm asking about the `Windows System tray icon` which are at the taskbar near the `clock`. they are still running programs which are not visible at the `windows taskbar` – Mohammad Faisal Sep 18 '11 at 14:25
  • @Mohammad Faisal undeleted now I hope that :-), all answerers (include me) have wrong day, my posts here are *** – mKorbel Sep 18 '11 at 14:28
  • @Andrew Thompson are we (I tried something to read and compared Java6 with Java7) sure that there isn't any changes in API, with my respect to your person, isn't too soon for that :-) :-), ... now my reason == I not sure with that then I posting here only link to the current Java6 Api's, – mKorbel Sep 18 '11 at 14:32
  • Hi guys, sorry for the quick hijack, I'm trying this example and I wanted to make it into an executable jar. I compiled it with ```javac WindowGCDemo1.java``` then I wrote a manifest.txt with Main-Class WindowGCDemo1, then I packed up a jar with ```jar cvfm Demo.jar manifest.txt WindowGCDemo1.class``` but when I launch it with ```java -jar Demo.jar``` I get ```Failed to load Main-Class manifest attribute```. Any quick though on why it's going like that? – jj_ Apr 26 '14 at 10:58
  • Just for the records, it was a matter of adding a new empty line to the manifest after the main-class line! Since I already "polluted" the comments I thought it could be a helpful thing to share. – jj_ Apr 26 '14 at 11:29
-2

Check the TryIconDemo from Documentation. This Link contain a small piece of code. Copy and Run it on your IDE.

https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/uiswing/examples/misc/TrayIconDemoProject/src/misc/TrayIconDemo.java

/*
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle or the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package misc;  
/*
 * TrayIconDemo.java
 */

import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;

public class TrayIconDemo {
    public static void main(String[] args) {
        /* Use an appropriate Look and Feel */
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            //UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        } catch (UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (InstantiationException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        /* Turn off metal's use of bold fonts */
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        //Schedule a job for the event-dispatching thread:
        //adding TrayIcon.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        //Check the SystemTray support
        if (!SystemTray.isSupported()) {
            System.out.println("SystemTray is not supported");
            return;
        }
        final PopupMenu popup = new PopupMenu();
        final TrayIcon trayIcon =
                new TrayIcon(createImage("images/bulb.gif", "tray icon"));
        final SystemTray tray = SystemTray.getSystemTray();

        // Create a popup 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 popup 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.");
            return;
        }

        trayIcon.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null,
                        "This dialog box is run from System Tray");
            }
        });

        aboutItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null,
                        "This dialog box is run from the About menu item");
            }
        });

        cb1.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                int cb1Id = e.getStateChange();
                if (cb1Id == ItemEvent.SELECTED){
                    trayIcon.setImageAutoSize(true);
                } else {
                    trayIcon.setImageAutoSize(false);
                }
            }
        });

        cb2.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                int cb2Id = e.getStateChange();
                if (cb2Id == ItemEvent.SELECTED){
                    trayIcon.setToolTip("Sun TrayIcon");
                } else {
                    trayIcon.setToolTip(null);
                }
            }
        });

        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                MenuItem item = (MenuItem)e.getSource();
                //TrayIcon.MessageType type = null;
                System.out.println(item.getLabel());
                if ("Error".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.ERROR;
                    trayIcon.displayMessage("Sun TrayIcon Demo",
                            "This is an error message", TrayIcon.MessageType.ERROR);

                } else if ("Warning".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.WARNING;
                    trayIcon.displayMessage("Sun TrayIcon Demo",
                            "This is a warning message", TrayIcon.MessageType.WARNING);

                } else if ("Info".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.INFO;
                    trayIcon.displayMessage("Sun TrayIcon Demo",
                            "This is an info message", TrayIcon.MessageType.INFO);

                } else if ("None".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.NONE;
                    trayIcon.displayMessage("Sun TrayIcon Demo",
                            "This is an ordinary message", TrayIcon.MessageType.NONE);
                }
            }
        };

        errorItem.addActionListener(listener);
        warningItem.addActionListener(listener);
        infoItem.addActionListener(listener);
        noneItem.addActionListener(listener);

        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                tray.remove(trayIcon);
                System.exit(0);
            }
        });
    }

    //Obtain the image URL
    protected static Image createImage(String path, String description) {
        URL imageURL = TrayIconDemo.class.getResource(path);

        if (imageURL == null) {
            System.err.println("Resource not found: " + path);
            return null;
        } else {
            return (new ImageIcon(imageURL, description)).getImage();
        }
    }
}
Tunaki
  • 116,530
  • 39
  • 281
  • 370
Aqeel Haider
  • 537
  • 5
  • 18