Java/SWT JFace Eclipse/Dialog — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 05:55, 1 июня 2010

A facade for the save FileDialog

//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import java.io.File;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
/**
 * This class provides a facade for the "save" FileDialog class. If the selected
 * file already exists, the user is asked to confirm before overwriting.
 */
public class SafeSaveDialog {
  // The wrapped FileDialog
  private FileDialog dlg;
  /**
   * SafeSaveDialog constructor
   * 
   * @param shell the parent shell
   */
  public SafeSaveDialog(Shell shell) {
    dlg = new FileDialog(shell, SWT.SAVE);
  }
  public String open() {
    // We store the selected file name in fileName
    String fileName = null;
    // The user has finished when one of the
    // following happens:
    // 1) The user dismisses the dialog by pressing Cancel
    // 2) The selected file name does not exist
    // 3) The user agrees to overwrite existing file
    boolean done = false;
    while (!done) {
      // Open the File Dialog
      fileName = dlg.open();
      if (fileName == null) {
        // User has cancelled, so quit and return
        done = true;
      } else {
        // User has selected a file; see if it already exists
        File file = new File(fileName);
        if (file.exists()) {
          // The file already exists; asks for confirmation
          MessageBox mb = new MessageBox(dlg.getParent(), SWT.ICON_WARNING
              | SWT.YES | SWT.NO);
          // We really should read this string from a
          // resource bundle
          mb.setMessage(fileName + " already exists. Do you want to replace it?");
          // If they click Yes, we"re done and we drop out. If
          // they click No, we redisplay the File Dialog
          done = mb.open() == SWT.YES;
        } else {
          // File does not exist, so drop out
          done = true;
        }
      }
    }
    return fileName;
  }
  public String getFileName() {
    return dlg.getFileName();
  }
  public String[] getFileNames() {
    return dlg.getFileNames();
  }
  public String[] getFilterExtensions() {
    return dlg.getFilterExtensions();
  }
  public String[] getFilterNames() {
    return dlg.getFilterNames();
  }
  public String getFilterPath() {
    return dlg.getFilterPath();
  }
  public void setFileName(String string) {
    dlg.setFileName(string);
  }
  public void setFilterExtensions(String[] extensions) {
    dlg.setFilterExtensions(extensions);
  }
  public void setFilterNames(String[] names) {
    dlg.setFilterNames(names);
  }
  public void setFilterPath(String string) {
    dlg.setFilterPath(string);
  }
  public Shell getParent() {
    return dlg.getParent();
  }
  public int getStyle() {
    return dlg.getStyle();
  }
  public String getText() {
    return dlg.getText();
  }
  public void setText(String string) {
    dlg.setText(string);
  }
}





Color Dialog Example

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class ColorDialogExample {
  Display d;
  Shell s;
  ColorDialogExample() {
    d = new Display();
    s = new Shell(d);
    s.setSize(400, 400);
    
    s.setText("A ColorDialog Example");
    s.setLayout(new FillLayout(SWT.VERTICAL));
    final Text t = new Text(s, SWT.BORDER | SWT.MULTI);
    final Button b = new Button(s, SWT.PUSH | SWT.BORDER);
    b.setText("Change Color");
    b.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        ColorDialog cd = new ColorDialog(s);
        cd.setText("ColorDialog Demo");
        cd.setRGB(new RGB(255, 255, 255));
        RGB newColor = cd.open();
        if (newColor == null) {
          return;
        }
        t.setBackground(new Color(d, newColor));
      }
    });
    s.open();
    while (!s.isDisposed()) {
      if (!d.readAndDispatch())
        d.sleep();
    }
    d.dispose();
  }
  public static void main(String[] argv) {
    new ColorDialogExample();
  }
}





Create a dialog shell (prompt for a value)

/*
 * Shell example snippet: create a dialog shell (prompt for a value)
 *
 * For a list of all SWT example snippets see
 * http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
 */
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
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 Snippet63 {
  public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.pack();
    shell.open();
    final boolean[] result = new boolean[1];
    final Shell dialog = new Shell(shell, SWT.DIALOG_TRIM
        | SWT.APPLICATION_MODAL);
    dialog.setLayout(new RowLayout());
    final Button ok = new Button(dialog, SWT.PUSH);
    ok.setText("Ok");
    Button cancel = new Button(dialog, SWT.PUSH);
    cancel.setText("Cancel");
    Listener listener = new Listener() {
      public void handleEvent(Event event) {
        result[0] = event.widget == ok;
        dialog.close();
      }
    };
    ok.addListener(SWT.Selection, listener);
    cancel.addListener(SWT.Selection, listener);
    dialog.pack();
    dialog.open();
    System.out.println("Prompt ...");
    while (!dialog.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    System.out.println("Result: " + result[0]);
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    display.dispose();
  }
}





Create a SWT dialog shell

/*
 * Shell example snippet: create a dialog shell
 *
 * For a list of all SWT example snippets see
 * http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
 */
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class Snippet50 {
  public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Shell");
    shell.setSize(200, 200);
    shell.open();
    Shell dialog = new Shell(shell);
    dialog.setText("Dialog");
    dialog.setSize(200, 200);
    dialog.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    display.dispose();
  }
}





Demonstrates FileDialog

//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import java.io.File;
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
 * This class demonstrates FileDialog
 */
public class ShowFileDialog {
  // These filter names are displayed to the user in the file dialog. Note that
  // the inclusion of the actual extension in parentheses is optional, and
  // doesn"t have any effect on which files are displayed.
  private static final String[] FILTER_NAMES = {
      "OpenOffice.org Spreadsheet Files (*.sxc)",
      "Microsoft Excel Spreadsheet Files (*.xls)",
      "Comma Separated Values Files (*.csv)", "All Files (*.*)"};
  // These filter extensions are used to filter which files are displayed.
  private static final String[] FILTER_EXTS = { "*.sxc", "*.xls", "*.csv", "*.*"};
  /**
   * Runs the application
   */
  public void run() {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("File Dialog");
    createContents(shell);
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    display.dispose();
  }
  /**
   * Creates the contents for the window
   * 
   * @param shell the parent shell
   */
  public void createContents(final Shell shell) {
    shell.setLayout(new GridLayout(5, true));
    new Label(shell, SWT.NONE).setText("File Name:");
    final Text fileName = new Text(shell, SWT.BORDER);
    GridData data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 4;
    fileName.setLayoutData(data);
    Button multi = new Button(shell, SWT.PUSH);
    multi.setText("Open Multiple...");
    multi.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        // User has selected to open multiple files
        FileDialog dlg = new FileDialog(shell, SWT.MULTI);
        dlg.setFilterNames(FILTER_NAMES);
        dlg.setFilterExtensions(FILTER_EXTS);
        String fn = dlg.open();
        if (fn != null) {
          // Append all the selected files. Since getFileNames() returns only 
          // the names, and not the path, prepend the path, normalizing
          // if necessary
          StringBuffer buf = new StringBuffer();
          String[] files = dlg.getFileNames();
          for (int i = 0, n = files.length; i < n; i++) {
            buf.append(dlg.getFilterPath());
            if (buf.charAt(buf.length() - 1) != File.separatorChar) {
              buf.append(File.separatorChar);
            }
            buf.append(files[i]);
            buf.append(" ");
          }
          fileName.setText(buf.toString());
        }
      }
    });
    Button open = new Button(shell, SWT.PUSH);
    open.setText("Open...");
    open.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        // User has selected to open a single file
        FileDialog dlg = new FileDialog(shell, SWT.OPEN);
        dlg.setFilterNames(FILTER_NAMES);
        dlg.setFilterExtensions(FILTER_EXTS);
        String fn = dlg.open();
        if (fn != null) {
          fileName.setText(fn);
        }
      }
    });
    Button save = new Button(shell, SWT.PUSH);
    save.setText("Save...");
    save.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        // User has selected to save a file
        FileDialog dlg = new FileDialog(shell, SWT.SAVE);
        dlg.setFilterNames(FILTER_NAMES);
        dlg.setFilterExtensions(FILTER_EXTS);
        String fn = dlg.open();
        if (fn != null) {
          fileName.setText(fn);
        }
      }
    });
  }
  /**
   * The application entry point
   * 
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    new ShowFileDialog().run();
  }
}





Demonstrates the ColorDialog class

//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
 * This class demonstrates the ColorDialog class
 */
public class ChooseColor {
  private Color color;
  /**
   * Runs the application
   */
  public void run() {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Color Chooser");
    createContents(shell);
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    // Dispose the color we created for the Label
    if (color != null) {
      color.dispose();
    }
    display.dispose();
  }
  /**
   * Creates the window contents
   * 
   * @param shell the parent shell
   */
  private void createContents(final Shell shell) {
    shell.setLayout(new GridLayout(2, false));
    // Start with Celtics green
    color = new Color(shell.getDisplay(), new RGB(0, 255, 0));
    // Use a label full of spaces to show the color
    final Label colorLabel = new Label(shell, SWT.NONE);
    colorLabel.setText("                              ");
    colorLabel.setBackground(color);
    Button button = new Button(shell, SWT.PUSH);
    button.setText("Color...");
    button.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        // Create the color-change dialog
        ColorDialog dlg = new ColorDialog(shell);
        // Set the selected color in the dialog from
        // user"s selected color
        dlg.setRGB(colorLabel.getBackground().getRGB());
        // Change the title bar text
        dlg.setText("Choose a Color");
        // Open the dialog and retrieve the selected color
        RGB rgb = dlg.open();
        if (rgb != null) {
          // Dispose the old color, create the
          // new one, and set into the label
          color.dispose();
          color = new Color(shell.getDisplay(), rgb);
          colorLabel.setBackground(color);
        }
      }
    });
  }
  /**
   * The application entry point
   * 
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    new ChooseColor().run();
  }
}





Demonstrates the custom InputDialog class

//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
 * This class demonstrates the custom InputDialog class
 */
public class ShowInputDialog {
  public void run() {
    Display display = new Display();
    Shell shell = new Shell(display);
    createContents(shell);
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    display.dispose();
  }
  private void createContents(final Shell parent) {
    parent.setLayout(new FillLayout(SWT.VERTICAL));
    final Label label = new Label(parent, SWT.NONE);
    Button button = new Button(parent, SWT.PUSH);
    button.setText("Push Me");
    button.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        // Create and display the InputDialog
        InputDialog dlg = new InputDialog(parent);
        String input = dlg.open();
        if (input != null) {
          // User clicked OK; set the text into the label
          label.setText(input);
          label.getParent().pack();
        }
      }
    });
  }
  public static void main(String[] args) {
    new ShowInputDialog().run();
  }
}





Demonstrates the DirectoryDialog class

//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
 * This class demonstrates the DirectoryDialog class
 */
public class ShowDirectoryDialog {
  /**
   * Runs the application
   */
  public void run() {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Directory Browser");
    createContents(shell);
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
  }
  /**
   * Creates the window contents
   * 
   * @param shell the parent shell
   */
  private void createContents(final Shell shell) {
    shell.setLayout(new GridLayout(6, true));
    new Label(shell, SWT.NONE).setText("Directory:");
    // Create the text box extra wide to show long paths
    final Text text = new Text(shell, SWT.BORDER);
    GridData data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 4;
    text.setLayoutData(data);
    // Clicking the button will allow the user
    // to select a directory
    Button button = new Button(shell, SWT.PUSH);
    button.setText("Browse...");
    button.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        DirectoryDialog dlg = new DirectoryDialog(shell);
        // Set the initial filter path according
        // to anything they"ve selected or typed in
        dlg.setFilterPath(text.getText());
        // Change the title bar text
        dlg.setText("SWT"s DirectoryDialog");
        // Customizable message displayed in the dialog
        dlg.setMessage("Select a directory");
        // Calling open() will open and run the dialog.
        // It will return the selected directory, or
        // null if user cancels
        String dir = dlg.open();
        if (dir != null) {
          // Set the text box to the new selection
          text.setText(dir);
        }
      }
    });
  }
  /**
   * The application entry point
   * 
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    new ShowDirectoryDialog().run();
  }
}





Demonstrates the FontDialog class

//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
 * This class demonstrates the FontDialog class
 */
public class ChooseFont {
  private Font font;
  private Color color;
  /**
   * Runs the application
   */
  public void run() {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Font Chooser");
    createContents(shell);
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    // Dispose the font and color we created
    if (font != null) font.dispose();
    if (color != null) color.dispose();
    display.dispose();
  }
  /**
   * Creates the window contents
   * 
   * @param shell the parent shell
   */
  private void createContents(final Shell shell) {
    shell.setLayout(new GridLayout(2, false));
    final Label fontLabel = new Label(shell, SWT.NONE);
    fontLabel.setText("The selected font");
    Button button = new Button(shell, SWT.PUSH);
    button.setText("Font...");
    button.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        // Create the color-change dialog
        FontDialog dlg = new FontDialog(shell);
        // Pre-fill the dialog with any previous selection
        if (font != null) dlg.setFontList(fontLabel.getFont().getFontData());
        if (color != null) dlg.setRGB(color.getRGB());
        if (dlg.open() != null) {
          // Dispose of any fonts or colors we have created
          if (font != null) font.dispose();
          if (color != null) color.dispose();
          // Create the new font and set it into the label
          font = new Font(shell.getDisplay(), dlg.getFontList());
          fontLabel.setFont(font);
          // Create the new color and set it
          color = new Color(shell.getDisplay(), dlg.getRGB());
          fontLabel.setForeground(color);
          // Call pack() to resize the window to fit the new font
          shell.pack();
        }
      }
    });
  }
  /**
   * The application entry point
   * 
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    new ChooseFont().run();
  }
}





Demonstrates the MessageBox class

//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
 * This class demonstrates the MessageBox class
 */
public class ShowMessageBox {
  // Strings to show in the Icon dropdown
  private static final String[] ICONS = { "SWT.ICON_ERROR",
      "SWT.ICON_INFORMATION", "SWT.ICON_QUESTION", "SWT.ICON_WARNING",
      "SWT.ICON_WORKING"};
  // Strings to show in the Buttons dropdown
  private static final String[] BUTTONS = { "SWT.OK", "SWT.OK | SWT.CANCEL",
      "SWT.YES | SWT.NO", "SWT.YES | SWT.NO | SWT.CANCEL",
      "SWT.RETRY | SWT.CANCEL", "SWT.ABORT | SWT.RETRY | SWT.IGNORE"};
  /**
   * Runs the application
   */
  public void run() {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Show Message Box");
    createContents(shell);
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    display.dispose();
  }
  /**
   * Creates the main window"s contents
   * 
   * @param shell the parent shell
   */
  private void createContents(final Shell shell) {
    shell.setLayout(new GridLayout(2, false));
    // Create the dropdown to allow icon selection
    new Label(shell, SWT.NONE).setText("Icon:");
    final Combo icons = new Combo(shell, SWT.DROP_DOWN | SWT.READ_ONLY);
    for (int i = 0, n = ICONS.length; i < n; i++)
      icons.add(ICONS[i]);
    icons.select(0);
    // Create the dropdown to allow button selection
    new Label(shell, SWT.NONE).setText("Buttons:");
    final Combo buttons = new Combo(shell, SWT.DROP_DOWN | SWT.READ_ONLY);
    for (int i = 0, n = BUTTONS.length; i < n; i++)
      buttons.add(BUTTONS[i]);
    buttons.select(0);
    // Create the entry field for the message
    new Label(shell, SWT.NONE).setText("Message:");
    final Text message = new Text(shell, SWT.BORDER);
    message.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    // Create the label to show the return from the open call
    new Label(shell, SWT.NONE).setText("Return:");
    final Label returnVal = new Label(shell, SWT.NONE);
    returnVal.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    // Create the button and event handler
    // to display the message box
    Button button = new Button(shell, SWT.PUSH);
    button.setText("Show Message");
    button.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        // Clear any previously returned value
        returnVal.setText("");
        // This will hold the style to pass to the MessageBox constructor
        int style = 0;
        // Determine which icon was selected and
        // add it to the style
        switch (icons.getSelectionIndex()) {
        case 0:
          style |= SWT.ICON_ERROR;
          break;
        case 1:
          style |= SWT.ICON_INFORMATION;
          break;
        case 2:
          style |= SWT.ICON_QUESTION;
          break;
        case 3:
          style |= SWT.ICON_WARNING;
          break;
        case 4:
          style |= SWT.ICON_WORKING;
          break;
        }
        // Determine which set of buttons was selected
        // and add it to the style
        switch (buttons.getSelectionIndex()) {
        case 0:
          style |= SWT.OK;
          break;
        case 1:
          style |= SWT.OK | SWT.CANCEL;
          break;
        case 2:
          style |= SWT.YES | SWT.NO;
          break;
        case 3:
          style |= SWT.YES | SWT.NO | SWT.CANCEL;
          break;
        case 4:
          style |= SWT.RETRY | SWT.CANCEL;
          break;
        case 5:
          style |= SWT.ABORT | SWT.RETRY | SWT.IGNORE;
          break;
        }
        // Display the message box
        MessageBox mb = new MessageBox(shell, style);
        mb.setText("Message from SWT");
        mb.setMessage(message.getText());
        int val = mb.open();
        String valString = "";
        switch (val) // val contains the constant of the selected button
        {
        case SWT.OK:
          valString = "SWT.OK";
          break;
        case SWT.CANCEL:
          valString = "SWT.CANCEL";
          break;
        case SWT.YES:
          valString = "SWT.YES";
          break;
        case SWT.NO:
          valString = "SWT.NO";
          break;
        case SWT.RETRY:
          valString = "SWT.RETRY";
          break;
        case SWT.ABORT:
          valString = "SWT.ABORT";
          break;
        case SWT.IGNORE:
          valString = "SWT.IGNORE";
          break;
        }
        returnVal.setText(valString);
      }
    });
  }
  /**
   * Application entry point
   * 
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    new ShowMessageBox().run();
  }
}





Dialog Example

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class DialogExample extends Dialog {
  DialogExample(Shell parent) {
    super(parent);
  }
  public String open() {
    Shell parent = getParent();
    Shell dialog = new Shell(parent, SWT.DIALOG_TRIM
        | SWT.APPLICATION_MODAL);
    dialog.setSize(100, 100);
    dialog.setText("Java Source and Support");
    dialog.open();
    Display display = parent.getDisplay();
    while (!dialog.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    return "After Dialog";
  }
  public static void main(String[] argv) {
    new DialogExample(new Shell());
  }
}





Dialog Examples

/*******************************************************************************
 * All Right Reserved. Copyright (c) 1998, 2004 Jackwind Li Guojie
 * 
 * Created on 2004-5-13 22:13:55 by JACK $Id$
 *  
 ******************************************************************************/

import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
public class DialogExamples extends ApplicationWindow {
  /**
   * @param parentShell
   */
  public DialogExamples(Shell parentShell) {
    super(parentShell);
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.eclipse.jface.window.Window#createContents(org.eclipse.swt.widgets.ruposite)
   */
  protected Control createContents(Composite parent) {
    Composite composite = new Composite(parent, SWT.NULL);
    composite.setLayout(new GridLayout());
    /* ------ MessageDialog ------------- */
    // openQuestion
    final Button buttonOpenMessage = new Button(composite, SWT.PUSH);
    buttonOpenMessage.setText("Demo: MessageDialog.openQuestion");
    buttonOpenMessage.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        
        boolean answer =
          MessageDialog.openQuestion(
            getShell(),
            "A Simple Question",
            "Is SWT/JFace your favorite Java UI framework?");
        System.out.println("Your answer is " + (answer ? "YES" : "NO"));
      }
    });
    final Button buttonMessageDialog = new Button(composite, SWT.PUSH);
    buttonMessageDialog.setText("Demo: new MessageDialog");
    buttonMessageDialog.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        MessageDialog dialog =
          new MessageDialog(
            getShell(),
            "Select your favorite Java UI framework",
            null,
            "Which one of the following is your favorite Java UI framework?",
            MessageDialog.QUESTION,
            new String[] { "AWT", "Swing", "SWT/JFace" },
            2);
        int answer = dialog.open();
        
        switch (answer) {
          case -1: // if the user closes the dialog without clicking any button.
            System.out.println("No selection");
            break;
            
          case 0 :
            System.out.println("Your selection is: AWT");
            break;
          case 1 :
            System.out.println("Your selection is: Swing");
            break;
          case 2 :
            System.out.println("Your selection is: SWT/JFace");
            break;
          
        }
      }
    });
    
    /* ------ InputDialog ------------- */
    final Button buttonInputDialog = new Button(composite, SWT.PUSH);
    buttonInputDialog.setText("Demo: InputDialog");
    buttonInputDialog.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        IInputValidator validator = new IInputValidator() {
          public String isValid(String newText) {
            if(newText.equalsIgnoreCase("SWT/JFace") ||
                newText.equalsIgnoreCase("AWT") ||
                newText.equalsIgnoreCase("Swing"))
              return null;
            else
              return "The allowed values are: SWT/JFace, AWT, Swing";
          }
        };
        InputDialog dialog = new InputDialog(getShell(), "Question", "What"s your favorite Java UI framework?", "SWT/JFace", validator);
        if(dialog.open() == Window.OK) {
          System.out.println("Your favorite Java UI framework is: " + dialog.getValue());
        }else{
          System.out.println("Action cancelled");
        }
      }
    });
    
    /* ------ ProgressMonitorDialog ------------- */
    final Button buttonProgressDialog = new Button(composite, SWT.PUSH);
    buttonProgressDialog.setText("Demo: ProgressMonitorDialog");
    buttonProgressDialog.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        IRunnableWithProgress runnableWithProgress = new IRunnableWithProgress() {
          public void run(IProgressMonitor monitor)
            throws InvocationTargetException, InterruptedException {
            monitor.beginTask("Number counting", 10);
            for(int i=0; i<10; i++) {
              if(monitor.isCanceled()) {
                monitor.done();
                return;
              }
                
              System.out.println("Count number: " + i);
              monitor.worked(1);
              Thread.sleep(500); // 0.5s.
            }
            monitor.done();
          }
        };
        
        ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell());
        try {
          dialog.run(true, true, runnableWithProgress);
        } catch (InvocationTargetException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        
        
      }
    });    
    return super.createContents(parent);
  }
  public static void main(String[] args) {
    ApplicationWindow window = new DialogExamples(null);
    window.setBlockOnOpen(true);
    window.open();
  }
}





Dialog Shell

/******************************************************************************
 * Copyright (c) 1998, 2004 Jackwind Li Guojie
 * All right reserved. 
 * 
 * Created on Jan 25, 2004 6:16:43 PM by JACK
 * $Id$
 * 
 * visit: http://www.asprise.ru/swt
 *****************************************************************************/

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class DialogShell {
  public DialogShell() {
    Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new RowLayout());
    shell.setSize(500, 200);
    final Button openDialog = new Button(shell, SWT.PUSH);
    openDialog.setText("Click here to rate this book ...");
    openDialog.addSelectionListener(new SelectionListener() {
      public void widgetSelected(SelectionEvent e) {
        final Shell dialog =
          new Shell(shell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
        dialog.setLayout(new RowLayout());
        final String[] ratings =
          new String[] {
            "Killer!",
            "Good stuff",
            "So-so",
            "Needs work" };
        final Button[] radios = new Button[ratings.length];
        for (int i = 0; i < ratings.length; i++) {
          radios[i] = new Button(dialog, SWT.RADIO);
          radios[i].setText(ratings[i]);
        }
        Button rateButton = new Button(dialog, SWT.PUSH);
        rateButton.setText("Rate!");
        rateButton.addSelectionListener(new SelectionListener() {
          public void widgetSelected(SelectionEvent e) {
            for (int i = 0; i < radios.length; i++)
              if (radios[i].getSelection())
                openDialog.setText("Rating: " + ratings[i]);
            dialog.close();
          }
          public void widgetDefaultSelected(SelectionEvent e) {
          }
        });
        dialog.pack();
        dialog.open();
        // Move the dialog to the center of the top level shell.
        Rectangle shellBounds = shell.getBounds();
        Point dialogSize = dialog.getSize();
        dialog.setLocation(
          shellBounds.x + (shellBounds.width - dialogSize.x) / 2,
          shellBounds.y + (shellBounds.height - dialogSize.y) / 2);
      }
      public void widgetDefaultSelected(SelectionEvent e) {
      }
    });
    shell.open();
    // Set up the event loop.
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        // If no more entries in event queue
        display.sleep();
      }
    }
    display.dispose();
  }
  private void init() {
  }
  public static void main(String[] args) {
    new DialogShell();
  }
}





File Dialog Example

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
public class FileDialogExample {
  Display d;
  Shell s;
  FileDialogExample() {
    d = new Display();
    s = new Shell(d);
    s.setSize(400, 400);
    
    s.setText("A MessageBox Example");
    //         create the menu system
    Menu m = new Menu(s, SWT.BAR);
    // create a file menu and add an exit item
    final MenuItem file = new MenuItem(m, SWT.CASCADE);
    file.setText("&File");
    final Menu filemenu = new Menu(s, SWT.DROP_DOWN);
    file.setMenu(filemenu);
    final MenuItem openItem = new MenuItem(filemenu, SWT.PUSH);
    openItem.setText("&Open\tCTRL+O");
    openItem.setAccelerator(SWT.CTRL + "O");
    final MenuItem saveItem = new MenuItem(filemenu, SWT.PUSH);
    saveItem.setText("&Save\tCTRL+S");
    saveItem.setAccelerator(SWT.CTRL + "S");
    final MenuItem separator = new MenuItem(filemenu, SWT.SEPARATOR);
    final MenuItem exitItem = new MenuItem(filemenu, SWT.PUSH);
    exitItem.setText("E&xit");
    class Open implements SelectionListener {
      public void widgetSelected(SelectionEvent event) {
        FileDialog fd = new FileDialog(s, SWT.OPEN);
        fd.setText("Open");
        fd.setFilterPath("C:/");
        String[] filterExt = { "*.txt", "*.doc", ".rtf", "*.*" };
        fd.setFilterExtensions(filterExt);
        String selected = fd.open();
        System.out.println(selected);
      }
      public void widgetDefaultSelected(SelectionEvent event) {
      }
    }
    class Save implements SelectionListener {
      public void widgetSelected(SelectionEvent event) {
        FileDialog fd = new FileDialog(s, SWT.SAVE);
        fd.setText("Save");
        fd.setFilterPath("C:/");
        String[] filterExt = { "*.txt", "*.doc", ".rtf", "*.*" };
        fd.setFilterExtensions(filterExt);
        String selected = fd.open();
        System.out.println(selected);
      }
      public void widgetDefaultSelected(SelectionEvent event) {
      }
    }
    openItem.addSelectionListener(new Open());
    saveItem.addSelectionListener(new Save());
    exitItem.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        MessageBox messageBox = new MessageBox(s, SWT.ICON_QUESTION
            | SWT.YES | SWT.NO);
        messageBox.setMessage("Do you really want to exit?");
        messageBox.setText("Exiting Application");
        int response = messageBox.open();
        if (response == SWT.YES)
          System.exit(0);
      }
    });
    s.setMenuBar(m);
    s.open();
    while (!s.isDisposed()) {
      if (!d.readAndDispatch())
        d.sleep();
    }
    d.dispose();
  }
  public static void main(String[] argv) {
    new FileDialogExample();
  }
}





Font Dialog Example

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FontDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class FontDialogExample {
  Display d;
  Shell s;
  FontDialogExample() {
    d = new Display();
    s = new Shell(d);
    s.setSize(400, 400);
    
    s.setText("A FontDialog Example");
    s.setLayout(new FillLayout(SWT.VERTICAL));
    final Text t = new Text(s, SWT.BORDER | SWT.MULTI);
    final Button b = new Button(s, SWT.PUSH | SWT.BORDER);
    b.setText("Change Font");
    b.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        FontDialog fd = new FontDialog(s, SWT.NONE);
        fd.setText("Select Font");
        fd.setRGB(new RGB(0, 0, 255));
        FontData defaultFont = new FontData("Courier", 10, SWT.BOLD);
        fd.setFontData(defaultFont);
        FontData newFont = fd.open();
        if (newFont == null)
          return;
        t.setFont(new Font(d, newFont));
        t.setForeground(new Color(d, fd.getRGB()));
      }
    });
    s.open();
    while (!s.isDisposed()) {
      if (!d.readAndDispatch())
        d.sleep();
    }
    d.dispose();
  }
  public static void main(String[] argv) {
    new FontDialogExample();
  }
}





How to create your own dialog classes

//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
 * This class demonstrates how to create your own dialog classes. It allows users
 * to input a String
 */
public class InputDialog extends Dialog {
  private String message;
  private String input;
  /**
   * InputDialog constructor
   * 
   * @param parent the parent
   */
  public InputDialog(Shell parent) {
    // Pass the default styles here
    this(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
  }
  /**
   * InputDialog constructor
   * 
   * @param parent the parent
   * @param style the style
   */
  public InputDialog(Shell parent, int style) {
    // Let users override the default styles
    super(parent, style);
    setText("Input Dialog");
    setMessage("Please enter a value:");
  }
  /**
   * Gets the message
   * 
   * @return String
   */
  public String getMessage() {
    return message;
  }
  /**
   * Sets the message
   * 
   * @param message the new message
   */
  public void setMessage(String message) {
    this.message = message;
  }
  /**
   * Gets the input
   * 
   * @return String
   */
  public String getInput() {
    return input;
  }
  /**
   * Sets the input
   * 
   * @param input the new input
   */
  public void setInput(String input) {
    this.input = input;
  }
  /**
   * Opens the dialog and returns the input
   * 
   * @return String
   */
  public String open() {
    // Create the dialog window
    Shell shell = new Shell(getParent(), getStyle());
    shell.setText(getText());
    createContents(shell);
    shell.pack();
    shell.open();
    Display display = getParent().getDisplay();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    // Return the entered value, or null
    return input;
  }
  /**
   * Creates the dialog"s contents
   * 
   * @param shell the dialog window
   */
  private void createContents(final Shell shell) {
    shell.setLayout(new GridLayout(2, true));
    // Show the message
    Label label = new Label(shell, SWT.NONE);
    label.setText(message);
    GridData data = new GridData();
    data.horizontalSpan = 2;
    label.setLayoutData(data);
    // Display the input box
    final Text text = new Text(shell, SWT.BORDER);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 2;
    text.setLayoutData(data);
    // Create the OK button and add a handler
    // so that pressing it will set input
    // to the entered value
    Button ok = new Button(shell, SWT.PUSH);
    ok.setText("OK");
    data = new GridData(GridData.FILL_HORIZONTAL);
    ok.setLayoutData(data);
    ok.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        input = text.getText();
        shell.close();
      }
    });
    // Create the cancel button and add a handler
    // so that pressing it will set input to null
    Button cancel = new Button(shell, SWT.PUSH);
    cancel.setText("Cancel");
    data = new GridData(GridData.FILL_HORIZONTAL);
    cancel.setLayoutData(data);
    cancel.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        input = null;
        shell.close();
      }
    });
    // Set the OK button as the default, so
    // user can type input and press Enter
    // to dismiss
    shell.setDefaultButton(ok);
  }
}





MessageBox Example

/******************************************************************************
 * All Right Reserved. 
 * Copyright (c) 1998, 2004 Jackwind Li Guojie
 * 
 * Created on Mar 18, 2004 12:03:07 AM by JACK
 * $Id$
 * 
 *****************************************************************************/
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
public class MessageBoxExample {
  Display display = new Display();
  Shell shell = new Shell(display);
  Button button;
  public MessageBoxExample() {
    button = new Button(shell, SWT.PUSH);
    
    button.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        MessageBox messageBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.ABORT | SWT.RETRY | SWT.IGNORE);
        
        messageBox.setText("Warning");
        messageBox.setMessage("Save the changes before exiting?");
        int buttonID = messageBox.open();
        switch(buttonID) {
          case SWT.YES:
            // saves changes ...
          case SWT.NO:
            // exits here ...
            break;
          case SWT.CANCEL:
            // does nothing ...
        }
        System.out.println(buttonID);
      }
    });
    
    button.setText("Click me!");
    
    button.setBounds(0, 0, 100, 30);
    shell.pack();
    shell.open();
    //textUser.forceFocus();
    // Set up the event loop.
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        // If no more entries in event queue
        display.sleep();
      }
    }
    display.dispose();
  }
  private void init() {
  }
  public static void main(String[] args) {
    new MessageBoxExample();
  }
}





Number Input Dialog

/*******************************************************************************
 * All Right Reserved. Copyright (c) 1998, 2004 Jackwind Li Guojie
 * 
 * Created on Mar 18, 2004 1:01:54 AM by JACK $Id$
 *  
 ******************************************************************************/

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class NumberInputDialog extends Dialog {
  Double value;
  /**
   * @param parent
   */
  public NumberInputDialog(Shell parent) {
    super(parent);
  }
  /**
   * @param parent
   * @param style
   */
  public NumberInputDialog(Shell parent, int style) {
    super(parent, style);
  }
  /**
   * Makes the dialog visible.
   * 
   * @return
   */
  public Double open() {
    Shell parent = getParent();
    final Shell shell =
      new Shell(parent, SWT.TITLE | SWT.BORDER | SWT.APPLICATION_MODAL);
    shell.setText("NumberInputDialog");
    shell.setLayout(new GridLayout(2, true));
    Label label = new Label(shell, SWT.NULL);
    label.setText("Please enter a valid number:");
    final Text text = new Text(shell, SWT.SINGLE | SWT.BORDER);
    final Button buttonOK = new Button(shell, SWT.PUSH);
    buttonOK.setText("Ok");
    buttonOK.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
    Button buttonCancel = new Button(shell, SWT.PUSH);
    buttonCancel.setText("Cancel");
    text.addListener(SWT.Modify, new Listener() {
      public void handleEvent(Event event) {
        try {
          value = new Double(text.getText());
          buttonOK.setEnabled(true);
        } catch (Exception e) {
          buttonOK.setEnabled(false);
        }
      }
    });
    buttonOK.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        shell.dispose();
      }
    });
    buttonCancel.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        value = null;
        shell.dispose();
      }
    });
    
    shell.addListener(SWT.Traverse, new Listener() {
      public void handleEvent(Event event) {
        if(event.detail == SWT.TRAVERSE_ESCAPE)
          event.doit = false;
      }
    });
    text.setText("");
    shell.pack();
    shell.open();
    Display display = parent.getDisplay();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    return value;
  }
  public static void main(String[] args) {
    Shell shell = new Shell();
    NumberInputDialog dialog = new NumberInputDialog(shell);
    System.out.println(dialog.open());
  }
}





Prevent escape from closing a SWT dialog

/*
 * Shell example snippet: prevent escape from closing a dialog
 *
 * For a list of all SWT example snippets see
 * http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
 */
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
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 Snippet4 {
  public static void main(String[] args) {
    Display display = new Display();
    final Shell shell = new Shell(display);
    Button b = new Button(shell, SWT.PUSH);
    b.setText("Open Dialog ...");
    b.pack();
    b.setLocation(10, 10);
    b.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent se) {
        Shell dialog = new Shell(shell, SWT.DIALOG_TRIM);
        dialog.addListener(SWT.Traverse, new Listener() {
          public void handleEvent(Event e) {
            if (e.detail == SWT.TRAVERSE_ESCAPE) {
              e.doit = false;
            }
          }
        });
        dialog.open();
      }
    });
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    display.dispose();
  }
}





Print Dialog Example

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class PrintDialogExample {
  Display d;
  Shell s;
  PrintDialogExample() {
    d = new Display();
    s = new Shell(d);
    s.setSize(400, 400);
    
    s.setText("A PrintDialog Example");
    s.setLayout(new FillLayout(SWT.VERTICAL));
    final Text t = new Text(s, SWT.BORDER | SWT.MULTI);
    final Button b = new Button(s, SWT.PUSH | SWT.BORDER);
    b.setText("Print");
    b.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        PrintDialog printDialog = new PrintDialog(s, SWT.NONE);
        printDialog.setText("Print");
        PrinterData printerData = printDialog.open();
        if (!(printerData == null)) {
          Printer p = new Printer(printerData);
          p.startJob("PrintJob");
          p.startPage();
          Rectangle trim = p.ruputeTrim(0, 0, 0, 0);
          Point dpi = p.getDPI();
          int leftMargin = dpi.x + trim.x;
          int topMargin = dpi.y / 2 + trim.y;
          GC gc = new GC(p);
          Font font = gc.getFont();
          String printText = t.getText();
          Point extent = gc.stringExtent(printText);
          gc.drawString(printText, leftMargin, topMargin
              + font.getFontData()[0].getHeight());
          p.endPage();
          gc.dispose();
          p.endJob();
          p.dispose();
        }
      }
    });
    s.open();
    while (!s.isDisposed()) {
      if (!d.readAndDispatch())
        d.sleep();
    }
    d.dispose();
  }
  public static void main(String[] argv) {
    new PrintDialogExample();
  }
}





Shell Dialog Example

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class ShellDialogExample {
  ShellDialogExample() {
    Display d = new Display();
    Shell s = new Shell(d);
    s.setSize(300, 300);
    s.open();
    DialogExample de = new DialogExample(s);
    String result = de.open();
    System.out.println(result);
    while (!s.isDisposed()) {
      if (!d.readAndDispatch())
        d.sleep();
    }
    d.dispose();
  }
  public static void main(String[] argv) {
    new ShellDialogExample();
  }
}
class DialogExample extends Dialog {
  DialogExample(Shell parent) {
    super(parent);
  }
  public String open() {
    Shell parent = getParent();
    Shell dialog = new Shell(parent, SWT.DIALOG_TRIM
        | SWT.APPLICATION_MODAL);
    dialog.setSize(100, 100);
    dialog.setText("Java Source and Support");
    dialog.open();
    Display display = parent.getDisplay();
    while (!dialog.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    return "After Dialog";
  }
  public static void main(String[] argv) {
    new DialogExample(new Shell());
  }
}





SWT Dialog Class

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class DialogClass {
  static boolean deleteFlag = false;
  public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Dialog Example");
    shell.setSize(300, 200);
    shell.open();
    final Button button = new Button(shell, SWT.PUSH);
    button.setText("Delete File");
    button.setBounds(20, 40, 80, 25);
    final Text text = new Text(shell, SWT.SHADOW_IN);
    text.setBounds(140, 40, 100, 25);
    final Shell dialog = new Shell(shell, SWT.APPLICATION_MODAL
        | SWT.DIALOG_TRIM);
    dialog.setText("Delete File");
    dialog.setSize(250, 150);
    final Button buttonOK = new Button(dialog, SWT.PUSH);
    buttonOK.setText("OK");
    buttonOK.setBounds(20, 55, 80, 25);
    Button buttonCancel = new Button(dialog, SWT.PUSH);
    buttonCancel.setText("Cancel");
    buttonCancel.setBounds(120, 55, 80, 25);
    final Label label = new Label(dialog, SWT.NONE);
    label.setText("Delete the file?");
    label.setBounds(20, 15, 100, 20);
    Listener listener = new Listener() {
      public void handleEvent(Event event) {
        if (event.widget == buttonOK) {
          deleteFlag = true;
        } else {
          deleteFlag = false;
        }
        dialog.close();
      }
    };
    buttonOK.addListener(SWT.Selection, listener);
    buttonCancel.addListener(SWT.Selection, listener);
    Listener buttonListener = new Listener() {
      public void handleEvent(Event event) {
        dialog.open();
      }
    };
    button.addListener(SWT.Selection, buttonListener);
    while (!dialog.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    if (deleteFlag) {
      text.setText("File deleted.");
    } else {
      text.setText("File not deleted.");
    }
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    display.dispose();
  }
}





TitleAreaDialog: MailDialog

import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
public class MailDialog extends TitleAreaDialog {
  // IDs for MailDialog buttons
  // We use large integers because we don"t want
  // to conflict with system constants
  public static final int OPEN = 9999;
  public static final int DELETE = 9998;
  // List widget
  List list;
  // Initial content of the list
  String[] items;
  // Selected items
  String[] itemsToOpen;
  /**
   * Constructor for MailDialog.
   * 
   * @param shell -
   *            Containing shell
   * @param items -
   *            Mail messages passed to the dialog
   */
  public MailDialog(Shell shell, String[] items) {
    super(shell);
    this.items = items;
  }
  /**
   * @see org.eclipse.jface.window.Window#create() We complete the dialog with
   *      a title and a message
   */
  public void create() {
    super.create();
    setTitle("Mail");
    setMessage("You have mail! \n It could be vital for this evening...");
  }
  /**
   * @see org.eclipse.jface.dialogs.Dialog#
   *      createDialogArea(org.eclipse.swt.widgets.ruposite) Here we fill the
   *      center area of the dialog
   */
  protected Control createDialogArea(Composite parent) {
    // Create new composite as container
    final Composite area = new Composite(parent, SWT.NULL);
    // We use a grid layout and set the size of the margins
    final GridLayout gridLayout = new GridLayout();
    gridLayout.marginWidth = 15;
    gridLayout.marginHeight = 10;
    area.setLayout(gridLayout);
    // Now we create the list widget
    list = new List(area, SWT.BORDER | SWT.MULTI);
    // We define a minimum width for the list
    final GridData gridData = new GridData();
    gridData.widthHint = 200;
    list.setLayoutData(gridData);
    // We add a SelectionListener
    list.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        // When the selection changes, we re-validate the list
        validate();
      }
    });
    // We add the initial mail messages to the list
    for (int i = 0; i < items.length; i++) {
      list.add(items[i]);
    }
    return area;
  }
  private void validate() {
    // We select the number of selected list entries
    boolean selected = (list.getSelectionCount() > 0);
    // We enable/disable the Open and Delete buttons
    getButton(OPEN).setEnabled(selected);
    getButton(DELETE).setEnabled(selected);
    if (!selected)
      // If nothing was selected, we set an error message
      setErrorMessage("Select at least one entry!");
    else
      // Otherwise we set the error message to null
      // to show the intial content of the message area
      setErrorMessage(null);
  }
  /**
   * @see org.eclipse.jface.dialogs.Dialog#
   *      createButtonsForButtonBar(org.eclipse.swt.widgets.ruposite) We
   *      replace the OK and Cancel buttons by our own creations We use the
   *      method createButton() (from Dialog), to create the new buttons
   */
  protected void createButtonsForButtonBar(Composite parent) {
    // Create Open button
    Button openButton = createButton(parent, OPEN, "Open", true);
    // Initially deactivate it
    openButton.setEnabled(false);
    // Add a SelectionListener
    openButton.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        // Retrieve selected entries from list
        itemsToOpen = list.getSelection();
        // Set return code
        setReturnCode(OPEN);
        // Close dialog
        close();
      }
    });
    // Create Delete button
    Button deleteButton = createButton(parent, DELETE, "Delete", false);
    deleteButton.setEnabled(false);
    // Add a SelectionListener
    deleteButton.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        // Get the indices of the selected entries
        int selectedItems[] = list.getSelectionIndices();
        // Remove all these entries
        list.remove(selectedItems);
        // Now re-validate the list because it has changed
        validate();
      }
    });
    // Create Cancel button
    Button cancelButton = createButton(parent, CANCEL, "Cancel", false);
    // Add a SelectionListener
    cancelButton.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        setReturnCode(CANCEL);
        close();
      }
    });
  }
  /**
   * Method getItemsToOpen.
   * 
   * @return String[] - the selected items
   */
  public String[] getItemsToOpen() {
    return itemsToOpen;
  }
}





Yes No Icon MessageBox

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
public class SWTMessageBoxExample {
  Display d;
  Shell s;
  SWTMessageBoxExample() {
    d = new Display();
    s = new Shell(d);
    s.setSize(400, 400);
    
    s.setText("A MessageBox Example");
    //         create the menu system
    Menu m = new Menu(s, SWT.BAR);
    // create a file menu and add an exit item
    final MenuItem file = new MenuItem(m, SWT.CASCADE);
    file.setText("&File");
    final Menu filemenu = new Menu(s, SWT.DROP_DOWN);
    file.setMenu(filemenu);
    final MenuItem exitItem = new MenuItem(filemenu, SWT.PUSH);
    exitItem.setText("E&xit");
    exitItem.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        MessageBox messageBox = new MessageBox(s, SWT.ICON_QUESTION
            | SWT.YES | SWT.NO);
        messageBox.setMessage("Do you really want to exit?");
        messageBox.setText("Exiting Application");
        int response = messageBox.open();
        if (response == SWT.YES)
          System.exit(0);
      }
    });
    s.setMenuBar(m);
    s.open();
    while (!s.isDisposed()) {
      if (!d.readAndDispatch())
        d.sleep();
    }
    d.dispose();
  }
  public static void main(String[] argv) {
    new SWTMessageBoxExample();
  }
}