Search code examples
javaswtapplication-close

How to minimize the application to system tray on close from ApplicationWindow object?


I am in process of compiling an open source backup application. I want the application not to be closed using X nor any key combination such as Alt+F4 in Windows. What I prefer would be minimizing the application to system tray in such cases.

I am new to Java and so far what I have tried are:

  • Setting the shell style: I can get the shell using getShell method of ApplicationWindow instance, which I can only manipulate to show no buttons at all (SWT.TITLE) or all of the buttons. No luck only hiding the X using setShellStyle(getShellStyle() & ~SWT.CLOSE);

  • Getting the JFrame list using (getFrames) method, and trying to manipulate the item at 0. However I could not find the setDefaultCloseOperation method of the object, which seems to resolve my minimizing to tray problem.

  • No luck getting the JFrame instance from ApplicationWindow neither, so I couldn't use the setDefaultCloseOperation method.


Solution

  • Here is how I resolved the issue after 2 days of research:

    Override the close method!

    public boolean close() {
    
        final Shell grandShell = this.getShell();
        grandShell.setVisible(false);
    
        Display display = Display.getCurrent();
    
        Tray tray = display.getSystemTray();
        if(tray != null) {
            TrayItem item = new TrayItem(tray, SWT.NONE);
            item.setImage(ArecaImages.ICO_SMALL);
            final Menu menu = new Menu(getShell(), SWT.POP_UP);
            MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
            menuItem.setText("Areca");
            menuItem.addListener (SWT.Selection, new Listener () {
                public void handleEvent (Event event) {
                    grandShell.setVisible(true);
                }
            });
            item.addListener (SWT.MenuDetect, new Listener () {
                public void handleEvent (Event event) {
                    menu.setVisible (true);
                }
            });
    
        }
    
        return true;