How to create CustomControl in SWT : Custom Control « SWT JFace Eclipse « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Collections Data Structure
8. Database SQL JDBC
9. Design Pattern
10. Development Class
11. Email
12. Event
13. File Input Output
14. Game
15. Hibernate
16. J2EE
17. J2ME
18. JDK 6
19. JSP
20. JSTL
21. Language Basics
22. Network Protocol
23. PDF RTF
24. Regular Expressions
25. Security
26. Servlets
27. Spring
28. Swing Components
29. Swing JFC
30. SWT JFace Eclipse
31. Threads
32. Tiny Application
33. Velocity
34. Web Services SOA
35. XML
Microsoft Office Word 2007 Tutorial
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Java » SWT JFace Eclipse » Custom ControlScreenshots 
How to create CustomControl in SWT
How to create CustomControl in SWT

/*******************************************************************************
 * Copyright (c) 2000, 2003 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabFolder2Adapter;
import org.eclipse.swt.custom.CTabFolderEvent;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.ArmEvent;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.HelpEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MenuAdapter;
import org.eclipse.swt.events.MenuEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TreeEvent;
import org.eclipse.swt.events.TypedEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Caret;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.CoolBar;
import org.eclipse.swt.widgets.CoolItem;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.FontDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Sash;
import org.eclipse.swt.widgets.Scale;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Slider;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.widgets.Widget;

public class CustomControlExample extends ControlExample {

  /**
   * Creates an instance of a CustomControlExample embedded inside the
   * supplied parent Composite.
   
   @param parent
   *            the container of the example
   */
  public CustomControlExample(Composite parent) {
    super(parent);
  }

  /**
   * Answers the set of example Tabs
   */
  Tab[] createTabs() {
    return new Tab[] { new CComboTab(this)new CLabelTab(this),
        new CTabFolderTab(this)new SashFormTab(this),
        new StyledTextTab(this)};
  }

  /**
   * Invokes as a standalone program.
   */
  public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    CustomControlExample instance = new CustomControlExample(shell);
    shell.setText(getResourceString("custom.window.title"));
    setShellSize(display, shell);
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    instance.dispose();
  }
}

/*******************************************************************************
 * Copyright (c) 2000, 2005 IBM Corporation and others. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 
 * Contributors: IBM Corporation - initial API and implementation
 ******************************************************************************/
class ControlExample {
  private ShellTab shellTab;

  private TabFolder tabFolder;

  Image images[];

  static final int ciClosedFolder = 0, ciOpenFolder = 1, ciTarget = 2;

  static final String[] imageLocations = "closedFolder.gif",
      "openFolder.gif""target.gif" };

  boolean startup = true;

  /**
   * Creates an instance of a ControlExample embedded inside the supplied
   * parent Composite.
   
   @param parent
   *            the container of the example
   */
  public ControlExample(Composite parent) {
    initResources();
    tabFolder = new TabFolder(parent, SWT.NONE);
    Tab[] tabs = createTabs();
    for (int i = 0; i < tabs.length; i++) {
      TabItem item = new TabItem(tabFolder, SWT.NONE);
      item.setText(tabs[i].getTabText());
      item.setControl(tabs[i].createTabFolderPage(tabFolder));
      item.setData(tabs[i]);
    }
    startup = false;
  }

  /**
   * Answers the set of example Tabs
   */
  Tab[] createTabs() {
    return new Tab[] { new ButtonTab(this)new CanvasTab(this),
        new ComboTab(this)new CoolBarTab(this)new DialogTab(this),
        new GroupTab(this)new LabelTab(this)new LinkTab(this),
        new ListTab(this)new MenuTab(this)new ProgressBarTab(this),
        new SashTab(this), shellTab = new ShellTab(this),
        new SliderTab(this)new SpinnerTab(this),
        new TabFolderTab(this)new TableTab(this)new TextTab(this),
        new ToolBarTab(this)new TreeTab(this)};
  }

  /**
   * Disposes of all resources associated with a particular instance of the
   * ControlExample.
   */
  public void dispose() {
    /*
     * Destroy any shells that may have been created by the Shells tab. When
     * a shell is disposed, all child shells are also disposed. Therefore it
     * is necessary to check for disposed shells in the shells list to avoid
     * disposing a shell twice.
     */
    if (shellTab != null)
      shellTab.closeAllShells();
    shellTab = null;
    tabFolder = null;
    freeResources();
  }

  /**
   * Frees the resources
   */
  void freeResources() {
    if (images != null) {
      for (int i = 0; i < images.length; ++i) {
        final Image image = images[i];
        if (image != null)
          image.dispose();
      }
      images = null;
    }
  }

  /**
   * Gets a string from the resource bundle. We don't want to crash because of
   * a missing String. Returns the key if not found.
   */
  static String getResourceString(String key) {
      return key;
  }

  /**
   * Gets a string from the resource bundle and binds it with the given
   * arguments. If the key is not found, return the key.
   */
  static String getResourceString(String key, Object[] args) {
    try {
      return MessageFormat.format(getResourceString(key), args);
    catch (MissingResourceException e) {
      return key;
    catch (NullPointerException e) {
      return "!" + key + "!";
    }
  }

  /**
   * Loads the resources
   */
  void initResources() {
    final Class clazz = ControlExample.class;
      try {
        if (images == null) {
          images = new Image[imageLocations.length];

          for (int i = 0; i < imageLocations.length; ++i) {
            InputStream sourceStream = clazz
                .getResourceAsStream(imageLocations[i]);
            ImageData source = new ImageData(sourceStream);
            ImageData mask = source.getTransparencyMask();
            images[inew Image(null, source, mask);
            try {
              sourceStream.close();
            catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
        return;
      catch (Throwable t) {
      }
    String error = "Unable to load resources";
    freeResources();
    throw new RuntimeException(error);
  }

  /**
   * Invokes as a standalone program.
   */
  public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    ControlExample instance = new ControlExample(shell);
    shell.setText(getResourceString("window.title"));
    setShellSize(display, shell);
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    instance.dispose();
  }

  /**
   * Grabs input focus.
   */
  public void setFocus() {
    tabFolder.setFocus();
  }

  /**
   * Sets the size of the shell to it's "packed" size, unless that makes it
   * bigger than the display, in which case set it to 9/10 of display size.
   */
  static void setShellSize(Display display, Shell shell) {
    Rectangle bounds = display.getBounds();
    Point size = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
    if (size.x > bounds.width)
      size.x = bounds.width * 10;
    if (size.y > bounds.height)
      size.y = bounds.height * 10;
    shell.setSize(size);
  }
}

/*******************************************************************************
 * Copyright (c) 2000, 2005 IBM Corporation and others. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 
 * Contributors: IBM Corporation - initial API and implementation
 ******************************************************************************/

class ShellTab extends Tab {
  /* Style widgets added to the "Style" groups, and "Other" group */
  Button noParentButton, parentButton;

  Button noTrimButton, closeButton, titleButton, minButton, maxButton,
      borderButton, resizeButton, onTopButton, toolButton;

  Button createButton, closeAllButton;

  Button modelessButton, primaryModalButton, applicationModalButton,
      systemModalButton;

  Button imageButton;

  Group parentStyleGroup, modalStyleGroup;

  /* Variables used to track the open shells */
  int shellCount = 0;

  Shell[] shells = new Shell[4];

  /**
   * Creates the Tab within a given instance of ControlExample.
   */
  ShellTab(ControlExample instance) {
    super(instance);
  }

  /**
   * Close all the example shells.
   */
  void closeAllShells() {
    for (int i = 0; i < shellCount; i++) {
      if (shells[i!= null & !shells[i].isDisposed()) {
        shells[i].dispose();
      }
    }
    shellCount = 0;
  }

  /**
   * Handle the Create button selection event.
   
   @param event
   *            org.eclipse.swt.events.SelectionEvent
   */
  public void createButtonSelected(SelectionEvent event) {

    /*
     * Remember the example shells so they can be disposed by the user.
     */
    if (shellCount >= shells.length) {
      Shell[] newShells = new Shell[shells.length + 4];
      System.arraycopy(shells, 0, newShells, 0, shells.length);
      shells = newShells;
    }

    /* Compute the shell style */
    int style = SWT.NONE;
    if (noTrimButton.getSelection())
      style |= SWT.NO_TRIM;
    if (closeButton.getSelection())
      style |= SWT.CLOSE;
    if (titleButton.getSelection())
      style |= SWT.TITLE;
    if (minButton.getSelection())
      style |= SWT.MIN;
    if (maxButton.getSelection())
      style |= SWT.MAX;
    if (borderButton.getSelection())
      style |= SWT.BORDER;
    if (resizeButton.getSelection())
      style |= SWT.RESIZE;
    if (onTopButton.getSelection())
      style |= SWT.ON_TOP;
    if (toolButton.getSelection())
      style |= SWT.TOOL;
    if (modelessButton.getSelection())
      style |= SWT.MODELESS;
    if (primaryModalButton.getSelection())
      style |= SWT.PRIMARY_MODAL;
    if (applicationModalButton.getSelection())
      style |= SWT.APPLICATION_MODAL;
    if (systemModalButton.getSelection())
      style |= SWT.SYSTEM_MODAL;

    /* Create the shell with or without a parent */
    if (noParentButton.getSelection()) {
      shells[shellCountnew Shell(style);
    else {
      Shell shell = tabFolderPage.getShell();
      shells[shellCountnew Shell(shell, style);
    }
    final Shell currentShell = shells[shellCount];
    Button button = new Button(currentShell, SWT.PUSH);
    button.setBounds(202012030);
    Button closeButton = new Button(currentShell, SWT.PUSH);
    closeButton.setBounds(1602012030);
    closeButton.setText(ControlExample.getResourceString("Close"));
    closeButton.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        currentShell.dispose();
      }
    });

    /* Set the size, title, and image, and open the shell */
    currentShell.setSize(300100);
    currentShell.setText(ControlExample.getResourceString("Title")
        + shellCount);
    if (imageButton.getSelection())
      currentShell.setImage(instance.images[ControlExample.ciTarget]);
    hookListeners(currentShell);
    currentShell.open();
    shellCount++;
  }

  /**
   * Creates the "Control" group.
   */
  void createControlGroup() {
    /*
     * Create the "Control" group. This is the group on the right half of
     * each example tab. It consists of the style group, the 'other' group
     * and the size group.
     */
    controlGroup = new Group(tabFolderPage, SWT.NONE);
    controlGroup.setLayout(new GridLayout(2true));
    controlGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL
        | GridData.VERTICAL_ALIGN_FILL));
    controlGroup.setText(ControlExample.getResourceString("Parameters"));

    /* Create a group for the decoration style controls */
    styleGroup = new Group(controlGroup, SWT.NONE);
    styleGroup.setLayout(new GridLayout());
    styleGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false,
        13));
    styleGroup.setText(ControlExample
        .getResourceString("Decoration_Styles"));

    /* Create a group for the modal style controls */
    modalStyleGroup = new Group(controlGroup, SWT.NONE);
    modalStyleGroup.setLayout(new GridLayout());
    modalStyleGroup.setLayoutData(new GridData(
        GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
    modalStyleGroup.setText(ControlExample
        .getResourceString("Modal_Styles"));

    /* Create a group for the 'other' controls */
    otherGroup = new Group(controlGroup, SWT.NONE);
    otherGroup.setLayout(new GridLayout());
    otherGroup
        .setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
    otherGroup.setText(ControlExample.getResourceString("Other"));

    /* Create a group for the parent style controls */
    parentStyleGroup = new Group(controlGroup, SWT.NONE);
    parentStyleGroup.setLayout(new GridLayout());
    GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    parentStyleGroup.setLayoutData(gridData);
    parentStyleGroup.setText(ControlExample.getResourceString("Parent"));
  }

  /**
   * Creates the "Control" widget children.
   */
  void createControlWidgets() {

    /* Create the parent style buttons */
    noParentButton = new Button(parentStyleGroup, SWT.RADIO);
    noParentButton.setText(ControlExample.getResourceString("No_Parent"));
    parentButton = new Button(parentStyleGroup, SWT.RADIO);
    parentButton.setText(ControlExample.getResourceString("Parent"));

    /* Create the decoration style buttons */
    noTrimButton = new Button(styleGroup, SWT.CHECK);
    noTrimButton.setText("SWT.NO_TRIM");
    closeButton = new Button(styleGroup, SWT.CHECK);
    closeButton.setText("SWT.CLOSE");
    titleButton = new Button(styleGroup, SWT.CHECK);
    titleButton.setText("SWT.TITLE");
    minButton = new Button(styleGroup, SWT.CHECK);
    minButton.setText("SWT.MIN");
    maxButton = new Button(styleGroup, SWT.CHECK);
    maxButton.setText("SWT.MAX");
    borderButton = new Button(styleGroup, SWT.CHECK);
    borderButton.setText("SWT.BORDER");
    resizeButton = new Button(styleGroup, SWT.CHECK);
    resizeButton.setText("SWT.RESIZE");
    onTopButton = new Button(styleGroup, SWT.CHECK);
    onTopButton.setText("SWT.ON_TOP");
    toolButton = new Button(styleGroup, SWT.CHECK);
    toolButton.setText("SWT.TOOL");

    /* Create the modal style buttons */
    modelessButton = new Button(modalStyleGroup, SWT.RADIO);
    modelessButton.setText("SWT.MODELESS");
    primaryModalButton = new Button(modalStyleGroup, SWT.RADIO);
    primaryModalButton.setText("SWT.PRIMARY_MODAL");
    applicationModalButton = new Button(modalStyleGroup, SWT.RADIO);
    applicationModalButton.setText("SWT.APPLICATION_MODAL");
    systemModalButton = new Button(modalStyleGroup, SWT.RADIO);
    systemModalButton.setText("SWT.SYSTEM_MODAL");

    /* Create the 'other' buttons */
    imageButton = new Button(otherGroup, SWT.CHECK);
    imageButton.setText(ControlExample.getResourceString("Image"));

    /* Create the "create" and "closeAll" buttons */
    createButton = new Button(controlGroup, SWT.NONE);
    GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_END);
    createButton.setLayoutData(gridData);
    createButton.setText(ControlExample.getResourceString("Create_Shell"));
    closeAllButton = new Button(controlGroup, SWT.NONE);
    gridData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
    closeAllButton.setText(ControlExample
        .getResourceString("Close_All_Shells"));
    closeAllButton.setLayoutData(gridData);

    /* Add the listeners */
    createButton.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        createButtonSelected(e);
      }
    });
    closeAllButton.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        closeAllShells();
      }
    });
    SelectionListener decorationButtonListener = new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        decorationButtonSelected(event);
      }
    };
    noTrimButton.addSelectionListener(decorationButtonListener);
    closeButton.addSelectionListener(decorationButtonListener);
    titleButton.addSelectionListener(decorationButtonListener);
    minButton.addSelectionListener(decorationButtonListener);
    maxButton.addSelectionListener(decorationButtonListener);
    borderButton.addSelectionListener(decorationButtonListener);
    resizeButton.addSelectionListener(decorationButtonListener);
    applicationModalButton.addSelectionListener(decorationButtonListener);
    systemModalButton.addSelectionListener(decorationButtonListener);

    /* Set the default state */
    noParentButton.setSelection(true);
    modelessButton.setSelection(true);
  }

  /**
   * Handle a decoration button selection event.
   
   @param event
   *            org.eclipse.swt.events.SelectionEvent
   */
  public void decorationButtonSelected(SelectionEvent event) {

    /*
     * Make sure if the modal style is SWT.APPLICATION_MODAL or
     * SWT.SYSTEM_MODAL the style SWT.CLOSE is also selected. This is to
     * make sure the user can close the shell.
     */
    Button widget = (Buttonevent.widget;
    if (widget == applicationModalButton || widget == systemModalButton) {
      if (widget.getSelection()) {
        closeButton.setSelection(true);
        noTrimButton.setSelection(false);
      }
      return;
    }
    if (widget == closeButton) {
      if (applicationModalButton.getSelection()
          || systemModalButton.getSelection()) {
        closeButton.setSelection(true);
      }
    }
    /*
     * Make sure if the No Trim button is selected then all other decoration
     * buttons are deselected.
     */
    if (widget.getSelection() && widget != noTrimButton) {
      noTrimButton.setSelection(false);
      return;
    }
    if (widget.getSelection() && widget == noTrimButton) {
      if (applicationModalButton.getSelection()
          || systemModalButton.getSelection()) {
        noTrimButton.setSelection(false);
        return;
      }
      closeButton.setSelection(false);
      titleButton.setSelection(false);
      minButton.setSelection(false);
      maxButton.setSelection(false