Search code examples
javaswingsystem-tray

How to trap the Window minimizing event?


I want to create a JFrame instance and on the click of its minimize button, I would like to hide it to the System Tray which is usually the taskbar of windows.

I'd come to know that by using SystemTray class in java.awt package I can do so but neither I'm getting any tutorial on it nor any working program example.

I'd asked this question here to either get the link to tutorial site for SystemTray class or if any body knows how to trap the window minimizing event, a working example.


Solution

  • This will trap the window minimized event and will create a tray icon. It will also remove the window from the taskbar and it will add a listener on the tray icon so that a mouseclick would restore the window. The code is a bit scrappy but should be good enough for your learning purposes:

    public class Qwe extends JFrame {
    
    public static void main(String[] args) {
        final Qwe qwe = new Qwe();
    
        qwe.addWindowStateListener(new WindowStateListener() {
            public void windowStateChanged(WindowEvent e) {
                if (e.getNewState() == ICONIFIED) {
                    try {
                        final TrayIcon trayIcon = new TrayIcon(new ImageIcon("/usr/share/icons/gnome/16x16/emotes/face-plain.png").getImage());
                        trayIcon.addMouseListener(new MouseAdapter() {
                            @Override
                            public void mouseClicked(MouseEvent e) {
                                qwe.setVisible(true);
                                SystemTray.getSystemTray().remove(trayIcon);
                            }
                        });
                        SystemTray.getSystemTray().add(trayIcon);
                        qwe.setVisible(false);
                    } catch (AWTException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        });
        qwe.setSize(200, 200);
        qwe.setVisible(true);
    }
    
    }