Java Tutorial/SWT/Shell Event
Add Close event for Shell window
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
public class ShellWindowCloseEvent {
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
shell.addListener(SWT.Close, new Listener() {
public void handleEvent(Event event) {
System.out.println("cose");
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Change the default behavior of shells
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.ShellListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
public class ShellBehaviourDefault {
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display, SWT.SHELL_TRIM);
shell.setLayout(new FillLayout());
shell.addShellListener(new ShellListener() {
public void shellActivated(ShellEvent event) {
}
public void shellClosed(ShellEvent event) {
MessageBox messageBox = new MessageBox(shell, SWT.APPLICATION_MODAL | SWT.YES | SWT.NO);
messageBox.setText("Warning");
messageBox.setMessage("You have unsaved data. Close the shell anyway?");
if (messageBox.open() == SWT.YES)
event.doit = true;
else
event.doit = false;
}
public void shellDeactivated(ShellEvent arg0) {
}
public void shellDeiconified(ShellEvent arg0) {
}
public void shellIconified(ShellEvent arg0) {
}
});
shell.open();
// Set up the event loop.
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
// If no more entries in event queue
display.sleep();
}
}
display.dispose();
}
}
Shell Events
Shells can generate a unique type of event: shell events (ShellEvent). A shell event is generated when a shell is minimized, maximized, activated, deactivated, or closed.
To add a shell listener to a shell, use this method:
public void addShellListener(ShellListener listener)