Creating an SWT table with the lines visible

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
  
public class Main {
   public static void main(String[] args) {
      Display display = new Display();
      Shell shell = new Shell(display);
  
      // pos x, pos y, width, height
      shell.setBounds(200, 200, 300, 200);
      shell.setText("SWT Table Demonstration");
      shell.setLayout(new GridLayout());
  
      Table table;
      String[] columnTitles = { "Wine", "Vintage", "Price" };
 
      Object[][] tabledata = {
            { "Chateau Meyney, St. Estephe",       new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe",     new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien",     new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
      };
  
      Group tableGroup = new Group(shell, SWT.NULL);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 1;
      tableGroup.setLayout(gridLayout);
      tableGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      tableGroup.setText("Table");
  
      table = new Table(tableGroup, SWT.FULL_SELECTION);
      table.setHeaderVisible(true);
      table.setLinesVisible(true);
        
      for (int i=0; i<columnTitles.length; i++) {
         TableColumn tableColumn = new TableColumn(table, SWT.NULL);
         tableColumn.setText(columnTitles[i]);
      }  
        
      for (int i=0; i<tabledata.length; i++) {
         TableItem tableItem = new TableItem (table, SWT.NULL);
         for (int j=0; j<columnTitles.length; j++) {
            tableItem.setText(j, ""+tabledata[i][j]);
         }
      }
  
      for (int i=0; i<columnTitles.length; i++) {
         TableColumn tableColumn = table.getColumn(i);
         tableColumn.pack();
      }      
        
      shell.open();
  
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      display.dispose();
   }
}

Using SWT JFace TreeViewer

Create a ContentProvider for the TreeViewer: implement the methods in ITreeContentProvider. The following example shows you how to do this. The business objects are Category and Link. (For an extension of this code, check the Q&A How do I use a Sash?

Category.java:

import java.util.*;
 
public class Category {
   private String name;
   private Category parent;
   private ArrayList categories = new ArrayList();
   private ArrayList links = new ArrayList();
   
   public Category(String name, Category parent) {
      this.name = name;
      this.parent = parent;
   }
   
   public void addSubCategory(Category category) {
      categories.add(category);
   }
   
   public void addLink(Link link) {
      links.add(link);
   }
   
   public ArrayList getSubCategories() {
      return categories;
   }
   
   public ArrayList getLinks() {
      return links;
   }
   
   public boolean hasSubCategories() {
      return categories.size() > 0;
   }
   
   public boolean hasLinks() {
      return links.size() > 0;
   }
   
   public String getName() {
      return name;
   }
   
   public Category getParent() {
      return parent;
   }
   
   public String toString() {
      return name;
   }
}

Link.java:

public class Link {
   private String url;
   
   public Link(String url) {
      this.url = url;
   }
   
   public String getUrl() {
      return url;
   }
   
   public String toString() {
      return url;
   }
}

CategoryTreeContentProvider.java:

import org.eclipse.jface.viewers.*;
import java.util.*;
 
public class CategoryTreeContentProvider implements ITreeContentProvider 
{
   public Object[] getChildren(Object element) {
      Category category = (Category) element;
      System.out.println(category.getName());
      
      ArrayList children = new ArrayList();
      children.addAll(category.getSubCategories());
      children.addAll(category.getLinks());
            
      if (children.size() == 0) {
         return new Object[0];
      }
      
      return children.toArray();
   }
   
   public Object[] getElements(Object element) {
      return getChildren(element);
   }
   
   public boolean hasChildren(Object element) {
      if (element instanceof Category) {
         Category category = (Category) element;
      
         return category.hasSubCategories() || category.hasLinks();
      }
      
      return false;
   }
   
   public Object getParent(Object element) {
      if (element instanceof Category) {
         return ((Category) element).getParent();
      }
      
      return null;
   }
   
   public void dispose() {
      
   }
   
   public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
      
   }
}

Main.java:

import org.eclipse.jface.viewers.*;
import org.eclipse.jface.window.*;
import org.eclipse.swt.widgets.*;
 
public class Main extends ApplicationWindow 
{
   private Category rootCategory;
   
   public Main() {
      super(null);
      
      // statically create categories
      rootCategory = new Category("Java", null);
      Category j2seCategory = new Category("J2SE", rootCategory);
      Link link = new Link("http://java.sun.com/j2se/");
      j2seCategory.addLink(link);
      Category j2eeCategory = new Category("J2EE", rootCategory);
      link = new Link("http://java.sun.com/j2se/");
      j2eeCategory.addLink(link);
      Category j2meCategory = new Category("J2ME", rootCategory);
      link = new Link("http://java.sun.com/j2se/");
      j2meCategory.addLink(link);
      
      rootCategory.addSubCategory(j2seCategory);
      rootCategory.addSubCategory(j2eeCategory);
      rootCategory.addSubCategory(j2meCategory);
   }
   
   protected Control createContents(Composite parent) {
      TreeViewer treeViewer = new TreeViewer(parent);
      treeViewer.setContentProvider(new CategoryTreeContentProvider());
      treeViewer.setInput(rootCategory);
      
      return treeViewer.getTree();
   }
   
   public static void main(String []args) {
      Main main = new Main();
      main.setBlockOnOpen(true);
      main.open();
      
      Display.getCurrent().dispose();
   }
}

The contents that is displayed in the tree using the toString() method in Category and Link. This is not a clean separation of model and view. Instead, you can use a LabelProvider, a helper class with a callback method getText(Element).

CategoryTreeLabelProvider.java:

import org.eclipse.jface.viewers.*;
 
public class CategoryTreeLabelProvider extends LabelProvider
{
   public String getText(Object element) {
      if (element instanceof Category) {
         return ((Category) element).getName();
      }
      else if (element instanceof Link) {
         return ((Link) element).getUrl();
      }
      
      return "" + element;
   }
}

Modify your Main class:

   treeViewer.setLabelProvider(new CategoryTreeLabelProvider());

Creating a label with SWT

Main.java:

import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.*;
 
public class Main {
   public static void main(String[] args) {
      Display display = new Display();
      Shell shell = new Shell(display);

      // pos x, pos y, width, height
      shell.setBounds(200, 200, 300, 200);
      shell.setText("Label Demonstration");
      shell.setLayout(new GridLayout());

      Label label = new Label(shell, SWT.CENTER);
      label.setText("This is a label");

      shell.open();

      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      display.dispose();
   }
}

Making an SWT combobox read-only

Main.java:

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.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;

public class Main {
   public static void main(String[] args) {
      Display display = new Display();
      Shell shell = new Shell(display);

      // pos x, pos y, width, height
      shell.setBounds(200, 200, 300, 200);
      shell.setText("SWT Simple Editable Combobox Demonstration");
      shell.setLayout(new GridLayout());

      String[] comboData = { "one", "two", "three", "four", "five",
                             "six", "seven", "eight", "nine", "ten",
                             "eleven", "twelve", "thirtheen", "fourteen",
                             "fifteen", "sixteen", "seventeen", "eighteen",
                             "nineteen", "twinty" };

      Group comboGroup = new Group(shell, SWT.NULL);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 1;
      comboGroup.setLayout(gridLayout);
      comboGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      comboGroup.setText("Non-Editable Combo");
      
      Combo combo = new Combo(comboGroup, SWT.DROP_DOWN | SWT.READ_ONLY);
      
      SelectionListener selectionListener = new SelectionAdapter () {
         public void widgetSelected(SelectionEvent event) {
            Combo combo = ((Combo) event.widget);
            System.out.print(combo.getText());
            System.out.println(" selected = " + combo.getSelection());
         };
      };
      combo.addSelectionListener(selectionListener);
      combo.setItems(comboData);
      
      shell.open();

      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      display.dispose();
   }
}

Creating an SWT Text(Area)

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
 
public class Main {
   public static void main(String[] args) {
      Display display = new Display();
      Shell shell = new Shell(display);
 
      // pos x, pos y, width, height
      shell.setBounds(200, 200, 300, 200);
      shell.setText("SWT Text Demonstration");
      shell.setLayout(new GridLayout());
 
      shell.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
 
      Text text = new Text(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.WRAP);
      text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
       
      text.setText("Did you know..." +
                   "nn" +
                   "It is impossible to lick your elbow." +
                   "nnnnnnnnnnnnnnn" +
                   "Over 75% of people who read thisn" +
                   "will try to lick their elbow.");
       
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
       
      display.dispose();
   }
}

Using an SWT Sash

Sash is the Swing equivalent of a JSplitPane. It is a widget that can be dragged to resize two areas in a GUI.

Here’s an example of a Sash in a JFace application.

Category.java:

import java.util.*;

public class Category {
   private String name;
   private Category parent;
   private ArrayList categories = new ArrayList();
   private ArrayList links = new ArrayList();
   
   public Category(String name, Category parent) {
      this.name = name;
      this.parent = parent;
   }
   
   public void addSubCategory(Category category) {
      categories.add(category);
   }
   
   public void addLink(Link link) {
      links.add(link);
   }
   
   public ArrayList getSubCategories() {
      return categories;
   }
   
   public ArrayList getLinks() {
      return links;
   }
   
   public boolean hasSubCategories() {
      return categories.size() > 0;
   }
   
   public boolean hasLinks() {
      return links.size() > 0;
   }
   
   public String getName() {
      return name;
   }
   
   public Category getParent() {
      return parent;
   }
}

Link.java:

public class Link {
   private String url;
   
   public Link(String url) {
      this.url = url;
   }
   
   public String getUrl() {
      return url;
   }
}

CategoryTreeContentProvider.java:

import org.eclipse.jface.viewers.*;
import java.util.*;

public class CategoryTreeContentProvider implements ITreeContentProvider 
{
   public Object[] getChildren(Object element) {
      Category category = (Category) element;
      System.out.println(category.getName());
      
      ArrayList children = new ArrayList();
      children.addAll(category.getSubCategories());
      children.addAll(category.getLinks());
            
      if (children.size() == 0) {
         return new Object[0];
      }
      
      return children.toArray();
   }
   
   public Object[] getElements(Object element) {
      return getChildren(element);
   }
   
   public boolean hasChildren(Object element) {
      if (element instanceof Category) {
         Category category = (Category) element;
      
         return category.hasSubCategories() || category.hasLinks();
      }
      
      return false;
   }
   
   public Object getParent(Object element) {
      if (element instanceof Category) {
         return ((Category) element).getParent();
      }
      
      return null;
   }
   
   public void dispose() {
      
   }
   
   public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
      
   }
}

CategoryTreeLabelProvider.java:

import org.eclipse.jface.viewers.*;

public class CategoryTreeLabelProvider extends LabelProvider
{
   public String getText(Object element) {
      if (element instanceof Category) {
         return ((Category) element).getName();
      }
      else if (element instanceof Link) {
         return ((Link) element).getUrl();
      }
      
      return "" + element;
   }
}

Main.java:

import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleAutomation;
import org.eclipse.swt.ole.win32.OleControlSite;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.ole.win32.Variant;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;

public class Main extends ApplicationWindow 
{
   private Category rootCategory;
   private OleAutomation automation = null;
   
   public Main() {
      super(null);
      
      // statically create categories
      rootCategory = new Category("Java", null);
      Category j2seCategory = new Category("J2SE", rootCategory);
      Link link = new Link("http://java.sun.com/j2se/");
      j2seCategory.addLink(link);
      Category j2eeCategory = new Category("J2EE", rootCategory);
      link = new Link("http://java.sun.com/j2ee/");
      j2eeCategory.addLink(link);
      Category j2meCategory = new Category("J2ME", rootCategory);
      link = new Link("http://java.sun.com/j2me/");
      j2meCategory.addLink(link);
      
      rootCategory.addSubCategory(j2seCategory);
      rootCategory.addSubCategory(j2eeCategory);
      rootCategory.addSubCategory(j2meCategory);
   }
   
   protected Control createContents(Composite parent) {
      SashForm sashForm = new SashForm(parent, SWT.HORIZONTAL | SWT.NULL);
      
      TreeViewer treeViewer = new TreeViewer(sashForm);
      treeViewer.setContentProvider(new CategoryTreeContentProvider());
      treeViewer.setLabelProvider(new CategoryTreeLabelProvider());
      treeViewer.setInput(rootCategory);
      
      createIEControl(sashForm);
      
      treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
         public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection selection = (IStructuredSelection) event.getSelection();
            
            Object selectedObject = selection.getFirstElement();
            if (selectedObject instanceof Link) {
               goUrl(((Link) selectedObject).getUrl());  
            }
         }
      });
      
      return sashForm;
   }
   
   public static void main(String []args) {
      Main main = new Main();
      main.setBlockOnOpen(true);
      main.open();
      
      Display.getCurrent().dispose();
   }
   
   private void createIEControl(Composite parent) {     
      OleFrame frame = new OleFrame(parent, SWT.BORDER);
      FormData formData = new FormData();
      formData.top = new FormAttachment(0, 10);
      formData.left = new FormAttachment(0, 100);
      formData.right = new FormAttachment(100, 0);
      formData.bottom = new FormAttachment(100, -10);
      frame.setLayoutData(formData);
   
      OleControlSite controlSite = new OleControlSite(frame, SWT.NONE, "Shell.Explorer");
      controlSite.doVerb(OLE.OLEIVERB_SHOW);
      automation = new OleAutomation(controlSite);
      int[] rgdispid = automation.getIDsOfNames(new String[]{"GoHome"});
      int dispIdMember = rgdispid[0];
      automation.invoke(dispIdMember);
   }
   
   public void goUrl(String url) {
      int[] rgdispid = automation.getIDsOfNames(new String[]{"Navigate"});
      int dispIdMember = rgdispid[0];
      Variant[] rgvarg = new Variant[1]; // this is the URL parameter
      rgvarg[0] = new Variant(url);
      Variant pVarResult = automation.invoke(dispIdMember, rgvarg);      
   }   
}

Creating a simple JFace ApplicationWindow

Make sure your classpath and library path includes the correct SWT and JFace libraries.

In my case:

   org.eclipse.ui_2.0.1/workbench.jar
   org.eclipse.swt.win32_2.0.1/ws/win32/swt.jar
   org.eclipse.core.runtime_2.0.1/runtime.jar

Main.java:

import org.eclipse.jface.window.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.*;
 
public class Main extends ApplicationWindow {
   public Main(Shell parent) {
      super(parent);
      setBlockOnOpen(true);
   }
   
   public static void main(String []args) {
      Display display = new Display();
      Shell shell = new Shell(display);
      
      Main main = new Main(shell);
      main.open();
   }
}

Creating an SWT ColorDialog

Main.java:

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.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
 
public class Main { 
   static Display display;
   static Shell shell;
   static Color color;
    
   public static void main(String[] args) {
      display = new Display();
      shell = new Shell(display);
 
      // pos x, pos y, width, height
      shell.setBounds(200, 200, 400, 200);
      shell.setText("SWT ColorDialog Demonstration");
      shell.setLayout(new GridLayout());
 
      Group buttonGroup = new Group(shell, SWT.NONE);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 3;
      buttonGroup.setLayout(gridLayout);
      buttonGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
       
      SelectionListener selectionListener = new SelectionAdapter () {
         public void widgetSelected(SelectionEvent event) {
            RGB rgb = openColorDialog(shell);
            if (rgb != null) {
               if (color != null && !color.isDisposed()) {
                  color.dispose();
               }
                
               color = new Color(display, rgb);
               shell.setBackground(color);
            }
         };
      };
 
      final Button colorDialogButton = new Button(buttonGroup, SWT.PUSH);
      colorDialogButton.setText("Open ColorDialog");
      colorDialogButton.addSelectionListener(selectionListener);
       
      shell.open();

      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      if (color != null && !color.isDisposed()) {
         color.dispose();
      }
      display.dispose();
   }
    
   public static RGB openColorDialog(Shell shell) {
      ColorDialog dialog = new ColorDialog (shell ,SWT.MODELESS);
      dialog.setRGB (new RGB (100, 100, 100));
      dialog.setText("Choose a color!");
      RGB result = dialog.open ();
       
      return result;
   }      
}

Creating an SWT Tree

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
 
public class Main {
   public static void main(String[] args) {
      Display display = new Display();
      Shell shell = new Shell(display);
 
      // pos x, pos y, width, height
      shell.setBounds(200, 200, 300, 200);
      shell.setText("SWT Tree Demonstration");
      shell.setLayout(new GridLayout());
 
      Tree tree = new Tree(shell, SWT.BORDER);
       
      TreeItem node1 = new TreeItem (tree, SWT.NULL);
      node1.setText("Java");
       
      TreeItem node2 = new TreeItem(node1, SWT.NULL);
      node2.setText("j2se");
      TreeItem node3 = new TreeItem(node1, SWT.NULL);
      node3.setText("j2ee");
      TreeItem node4 = new TreeItem(node1, SWT.NULL);
      node4.setText("j2me");
       
      TreeItem node5 = new TreeItem(node2, SWT.NULL);
      node5.setText("http://java.sun.com/j2se/");
 
      TreeItem node6 = new TreeItem(node3, SWT.NULL);
      node6.setText("http://java.sun.com/j2se/");
  
      TreeItem node7 = new TreeItem(node4, SWT.NULL);
      node7.setText("http://java.sun.com/j2se/");
       
      tree.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
             
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
       
      display.dispose();
   }
}

Creating a JFace ApplicationWindow with MenuBar

Main.java:

import org.eclipse.jface.dialogs.*;
import org.eclipse.jface.action.*;
import org.eclipse.jface.window.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.*;
 
public class Main extends ApplicationWindow {
   public Main(Shell parent) {
      super(parent);
   }
   
   public static void main(String []args) {
      Display display = new Display();
      Shell shell = new Shell(display);
      
      Main main = new Main(shell);
      main.createComponents();
      main.open();
   }
 
   public void createComponents() {
      setBlockOnOpen(true);
      addMenuBar();
   }
   
   protected MenuManager createMenuManager() {
      MenuManager menuManager = new MenuManager();
      menuManager.add(createFileMenu());
      return menuManager;
   }
   
   protected MenuManager createFileMenu() {
      MenuManager menu = new MenuManager("&File", "Id01");

      menu.add(new Action() {
         public String getText() {
            return "&Open";
         }
         
         public void run() {
            String[] buttons = { IDialogConstants.OK_LABEL,
                                  IDialogConstants.CANCEL_LABEL };
            MessageDialog dialog = new MessageDialog(getShell(), "Title", null, 
                                                     "File/Open selected!", 
                                                     MessageDialog.INFORMATION, buttons, 0);
            dialog.open();   // blocking call
         }
      });

      menu.add(new Action() {
         public String getText() {
            return "E&xit";
         }
         
         public void run() {
            Main.this.getParentShell().close();
         }
      });
       
      return menu;
   }
    
   protected void configureShell(Shell shell) {
      super.configureShell(shell);
      shell.setSize(300, 200);
      shell.setText("Example JFace with MenuBar");
   }  
}