Question

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.

Was it helpful?

Solution 2

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;

OTHER TIPS

What I do is to use a hidden shell as the main window and let the application windows close normally. Something like:

// Main shell

Shell shell = new Shell(display, SWT.NO_TRIM);

shell.setBounds(0, 0, 0, 0);

shell.open();

shell.setVisible(false);

// Add system tray

Tray tray = display.getSystemTray();

TrayItem item = new TrayItem(tray, SWT.NONE);

item.setImage(image);

// System tray menu

final Menu menu = new Menu(shell, SWT.POP_UP);

MenuItem exitItem = new MenuItem(menu, SWT.PUSH);
exitItem.setText("Exit");

exitItem.addSelectionListener(new ExitListener());

item.addMenuDetectListener(new MenuDetectListener()
  {
    @Override
    public void menuDetected(MenuDetectEvent e)
    {
      menu.setVisible(true);
    }
  });

// Main loop

while (!shell.isDisposed())
 {
   if (!display.readAndDispatch())
     display.sleep();
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top