Creating a smooth ProgressBar in SWT

Main.java:

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
 
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
 
public class Main {
   private DownloadThread downloadThread = null;
   private boolean disposed = false;
    
   public Main() {
      final Display display = new Display();
      Shell shell = new Shell(display);
      shell.setText("SWT Smooth ProgressBar Demonstration");

      shell.setLayout(new FormLayout());
      shell.setBounds(200, 200, 700, 200);
       
      Label downloadLabel = new Label(shell, SWT.NONE);
      FormData data0 = new FormData();
      data0.left = new FormAttachment(0, 0);
      //data0.top = new FormAttachment(localLabel, 15);
      //data2.right = new FormAttachment(100, -100);
      downloadLabel.setLayoutData(data0);
      downloadLabel.setText("FTP file: ");
 
      final Text downloadField = new Text(shell, SWT.SINGLE | SWT.BORDER);
      FormData data1 = new FormData();
      data1.left = new FormAttachment(downloadLabel, 15);
      data1.right = new FormAttachment(100, -100);
      downloadField.setLayoutData(data1);
      downloadField.setText("ftp://ftp.mozilla.org/pub/mozilla/moz-sol/1.2a-02-09-25/mozilla-sparc-sun-solaris2.7.tar.gz");
            
      Label localLabel = new Label(shell, SWT.NONE);
      FormData data2 = new FormData();
      data2.left = new FormAttachment(0, 0);
      data2.top = new FormAttachment(localLabel, 15);
      localLabel.setLayoutData(data2);
      localLabel.setText("Save As: ");
      
      final Text localField = new Text(shell, SWT.SINGLE | SWT.BORDER);
      FormData data3 = new FormData();
      data3.left = new FormAttachment(localLabel, 15);
      data3.top = new FormAttachment(downloadField, 5);
      data3.right = new FormAttachment(100, -400);
      localField.setLayoutData(data3);
      localField.setText("c:\temp\tmp.bin");
      
      final Button downloadButton = new Button(shell, SWT.NONE);
      FormData data4 = new FormData();
      data4.left = new FormAttachment(downloadField, 5);
      data4.right = new FormAttachment(100, -5);
      downloadButton.setLayoutData(data4);
      downloadButton.setText("Download");
      
      Label progressLabel = new Label(shell, SWT.NONE);
      progressLabel.setText("Download progress:");
      FormData data5 = new FormData();
      data5.top = new FormAttachment(localField, 15);
      data5.left = new FormAttachment(10, 15);      
      data5.right = new FormAttachment(90, -15);
      progressLabel.setLayoutData(data5);      
             
      final ProgressBar progressBar = new ProgressBar(shell, SWT.SMOOTH);
      FormData data6 = new FormData();
      data6.top = new FormAttachment(localField, 35);
      data6.left = new FormAttachment(10, 15);      
      data6.right = new FormAttachment(90, -15);
      progressBar.setLayoutData(data6);
 
      shell.open();
 
      final DownloadListener downloadListener = new DownloadListener() {
         public void setMinimum(final int min) {
            display.asyncExec(new Runnable() {
               public void run() {
                  if (!disposed) {
                     progressBar.setMinimum(min);
                  }
               }
            });
         }
         
         public void setMaximum(final int max) {
            display.asyncExec(new Runnable() {
               public void run() {
                  if (!disposed) {
                     progressBar.setMaximum(max);
                  }
               }
            });
         }
         
         public void setSelection(final int selection) {
            display.asyncExec(new Runnable() {
               public void run() {
                  if (!disposed) {
                     progressBar.setSelection(selection);
                  }
               }
            });
         }
         
         public void downloadEnded() {
            if (!disposed) {
               display.asyncExec(new Runnable() {
                  public void run() {
                     System.out.println("disposed = " + disposed);
                     if (!disposed) {                  
                        downloadButton.setText("Download");  
                     }
                  }
               });
            }
         }
      };
      
      downloadButton.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(SelectionEvent event) {
            try {
               Button button = (Button) event.getSource();
               if (button.getText().equalsIgnoreCase("download")) {
                  if (downloadField.getText().trim().equals("")) return;
                  
                  File localFile = new File(localField.getText());
                  downloadThread = new DownloadThread(downloadListener, 
                                                      localFile,
                                                      new URL(downloadField.getText()));
                  downloadThread.start();
                  downloadButton.setText("Stop");
               }
               else {
                  downloadThread.terminate();
               }
            }
            catch(MalformedURLException e) {
               e.printStackTrace();
            }
         };
      });
 
      shell.addShellListener(new ShellAdapter() {
         public void shellClosed(ShellEvent se) {
            disposed = true;     
            if (downloadThread != null) {         
               downloadThread.terminate();
            }
         }
      });        
      
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      
      display.dispose();
   }
   
   public static void main(String[] args) {
      new Main();
   }
}
 
interface DownloadListener {
   public void setMinimum(int min);
   public void setMaximum(int max);
   public void setSelection(int selection);
   public void downloadEnded();
}
 
class DownloadThread extends Thread
{
   private int length = 0;
   private URL url = null;
   private File localFile = null;
   private DownloadListener listener = null;
   private boolean terminated = false;
   
   public DownloadThread(DownloadListener listener, File localFile, URL url) {
      this.url = url;
      this.localFile = localFile;
      this.listener = listener;
   }
   
   public void terminate() {
      terminated = true;
   }
   
   public void run() {
      try {
         System.out.println(url);
         URLConnection con = url.openConnection();
         System.out.println("Connecting...");
         con.connect();
         System.out.println("Connected!");
         int length = con.getContentLength();
 
         listener.setMinimum(0);
         listener.setMaximum(length);
          
         int block = 4096;
         int count = 0;
         FileOutputStream fos = new FileOutputStream(localFile);
         InputStream is = con.getInputStream();
         byte[] buff = new byte[block];
         int read = 0;
 
         listener.setSelection(0);
         while((read = is.read(buff, 0, block)) != -1) {
            byte[] bytes;
            if(read != buff.length) {
               bytes = new byte[read];
               System.arraycopy(buff, 0, bytes, 0, read);
            } 
            else {
               bytes = buff;
            }
            fos.write(bytes);
            count += read;
           
            if (terminated) {
               break;
            }
 
            listener.setSelection(count);
         }
         fos.flush();
         fos.close();
         
         listener.downloadEnded();
      } catch(Exception e) {
         System.out.println("Error downloading file " + url);
         e.printStackTrace();
      }
   }
}

Creating a ProgressBar in SWT

Main.java:

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
 
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
 
public class Main {
   private DownloadThread downloadThread = null;
   private boolean disposed = false;
    
   public Main() {
      final Display display = new Display();
      Shell shell = new Shell(display);
      shell.setText("SWT ProgressBar Demonstration");

      shell.setLayout(new FormLayout());
      shell.setBounds(200, 200, 700, 200);
       
      Label downloadLabel = new Label(shell, SWT.NONE);
      FormData data0 = new FormData();
      data0.left = new FormAttachment(0, 0);
      downloadLabel.setLayoutData(data0);
      downloadLabel.setText("FTP file: ");
 
      final Text downloadField = new Text(shell, SWT.SINGLE | SWT.BORDER);
      FormData data1 = new FormData();
      data1.left = new FormAttachment(downloadLabel, 15);
      data1.right = new FormAttachment(100, -100);
      downloadField.setLayoutData(data1);
      downloadField.setText("ftp://ftp.mozilla.org/pub/mozilla/moz-sol/1.2a-02-09-25/mozilla-sparc-sun-solaris2.7.tar.gz");
            
      Label localLabel = new Label(shell, SWT.NONE);
      FormData data2 = new FormData();
      data2.left = new FormAttachment(0, 0);
      data2.top = new FormAttachment(localLabel, 15);
      localLabel.setLayoutData(data2);
      localLabel.setText("Save As: ");
      
      final Text localField = new Text(shell, SWT.SINGLE | SWT.BORDER);
      FormData data3 = new FormData();
      data3.left = new FormAttachment(localLabel, 15);
      data3.top = new FormAttachment(downloadField, 5);
      data3.right = new FormAttachment(100, -400);
      localField.setLayoutData(data3);
      localField.setText("c:\temp\tmp.bin");
      
      final Button downloadButton = new Button(shell, SWT.NONE);
      FormData data4 = new FormData();
      data4.left = new FormAttachment(downloadField, 5);
      data4.right = new FormAttachment(100, -5);
      downloadButton.setLayoutData(data4);
      downloadButton.setText("Download");
      
      Label progressLabel = new Label(shell, SWT.NONE);
      progressLabel.setText("Download progress:");
      FormData data5 = new FormData();
      data5.top = new FormAttachment(localField, 15);
      data5.left = new FormAttachment(10, 15);      
      data5.right = new FormAttachment(90, -15);
      progressLabel.setLayoutData(data5);      
             
      final ProgressBar progressBar = new ProgressBar(shell, SWT.NONE);
      FormData data6 = new FormData();
      data6.top = new FormAttachment(localField, 35);
      data6.left = new FormAttachment(10, 15);      
      data6.right = new FormAttachment(90, -15);
      progressBar.setLayoutData(data6);
 
      shell.open();
 
      final DownloadListener downloadListener = new DownloadListener() {
         public void setMinimum(final int min) {
            display.asyncExec(new Runnable() {
               public void run() {
                  if (!disposed) {
                     progressBar.setMinimum(min);
                  }
               }
            });
         }
         
         public void setMaximum(final int max) {
            display.asyncExec(new Runnable() {
               public void run() {
                  if (!disposed) {
                     progressBar.setMaximum(max);
                  }
               }
            });
         }
         
         public void setSelection(final int selection) {
            display.asyncExec(new Runnable() {
               public void run() {
                  if (!disposed) {
                     progressBar.setSelection(selection);
                  }
               }
            });
         }
         
         public void downloadEnded() {
            if (!disposed) {
               display.asyncExec(new Runnable() {
                  public void run() {
                     System.out.println("disposed = " + disposed);
                     if (!disposed) {                  
                        downloadButton.setText("Download");  
                     }
                  }
               });
            }
         }
      };
      
      downloadButton.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(SelectionEvent event) {
            try {
               Button button = (Button) event.getSource();
               if (button.getText().equalsIgnoreCase("download")) {
                  if (downloadField.getText().trim().equals("")) return;
                  
                  File localFile = new File(localField.getText());
                  downloadThread = new DownloadThread(downloadListener, 
                                                      localFile,
                                                      new URL(downloadField.getText()));
                  downloadThread.start();
                  downloadButton.setText("Stop");
               }
               else {
                  downloadThread.terminate();
               }
            }
            catch(MalformedURLException e) {
               e.printStackTrace();
            }
         };
      });
 
      shell.addShellListener(new ShellAdapter() {
         public void shellClosed(ShellEvent se) {
            disposed = true;     
            if (downloadThread != null) {         
               downloadThread.terminate();
            }
         }
      });        
      
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      
      display.dispose();
   }
   
   public static void main(String[] args) {
      new Main();
   }
}
 
interface DownloadListener {
   public void setMinimum(int min);
   public void setMaximum(int max);
   public void setSelection(int selection);
   public void downloadEnded();
}
 
class DownloadThread extends Thread
{
   private int length = 0;
   private URL url = null;
   private File localFile = null;
   private DownloadListener listener = null;
   private boolean terminated = false;
   
   public DownloadThread(DownloadListener listener, File localFile, URL url) {
      this.url = url;
      this.localFile = localFile;
      this.listener = listener;
   }
   
   public void terminate() {
      terminated = true;
   }
   
   public void run() {
      try {
         System.out.println(url);
         URLConnection con = url.openConnection();
         System.out.println("Connecting...");
         con.connect();
         System.out.println("Connected!");
         int length = con.getContentLength();
 
         listener.setMinimum(0);
         listener.setMaximum(length);
          
         int block = 4096;
         int count = 0;
         FileOutputStream fos = new FileOutputStream(localFile);
         InputStream is = con.getInputStream();
         byte[] buff = new byte[block];
         int read = 0;
 
         listener.setSelection(0);
         while((read = is.read(buff, 0, block)) != -1) {
            byte[] bytes;
            if(read != buff.length) {
               bytes = new byte[read];
               System.arraycopy(buff, 0, bytes, 0, read);
            } 
            else {
               bytes = buff;
            }
            fos.write(bytes);
            count += read;
           
            if (terminated) {
               break;
            }
 
            listener.setSelection(count);
         }
         fos.flush();
         fos.close();
         
         listener.downloadEnded();
      } catch(Exception e) {
         System.out.println("Error downloading file " + url);
         e.printStackTrace();
      }
   }
}

Setting the alignment on a Label in SWT

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.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
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("Label Demonstration");
      shell.setLayout(new GridLayout());
             
      final Label label = new Label(shell, SWT.BORDER | SWT.WRAP);
      label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
      label.setText("`I quite agree with you,' said the Duchess; `and the moral " +
                    "of that is--Be what you would seem to be--or if you'd like " +
                    "it put more simply--Never imagine yourself not to be " +
                    "otherwise than what it might appear to others that what " +
                    "you were or might have been was not otherwise than what " +
                    "you had been would have appeared to them to be otherwise.'");
       
      Group buttonGroup = new Group(shell, SWT.NONE);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 1;
      buttonGroup.setLayout(gridLayout);
      buttonGroup.setLayoutData(new GridData(GridData.FILL_VERTICAL));
       
      SelectionListener selectionListener = new SelectionAdapter () {
         public void widgetSelected(SelectionEvent event) {
            Button button = ((Button) event.widget);
            if (button.getText().equals("Left")) {
               label.setAlignment(SWT.LEFT);
            }
            else if (button.getText().equals("Right")) {
               label.setAlignment(SWT.RIGHT);
            }
            else {
               label.setAlignment(SWT.CENTER);
            }
         };
      };
             
      Button leftAlign = new Button(buttonGroup, SWT.RADIO);
      leftAlign.setText("Left");
      leftAlign.addSelectionListener(selectionListener);
      Button centerAlign = new Button(buttonGroup, SWT.RADIO);
      centerAlign.setText("Center");
      centerAlign.addSelectionListener(selectionListener);
      Button rightAlign = new Button(buttonGroup, SWT.RADIO);
      rightAlign.setText("Right");
      rightAlign.addSelectionListener(selectionListener);
 
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      display.dispose();
   }
}

Creating a wrapped label in 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.BORDER | SWT.WRAP);
      label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
      label.setText("`I quite agree with you,' said the Duchess; `and the moral " +
                    "of that is--Be what you would seem to be--or if you'd like " +
                    "it put more simply--Never imagine yourself not to be " +
                    "otherwise than what it might appear to others that what " +
                    "you were or might have been was not otherwise than what " +
                    "you had been would have appeared to them to be otherwise.'");
 
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      display.dispose();
   }
}

Creating a coolbar in SWT

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.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.CoolBar;
import org.eclipse.swt.widgets.CoolItem;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
 
public class Main {
   public static void main (String [] args) {
      Display display = new Display ();
      Shell shell = new Shell (display);
      shell.setLayout(new GridLayout());
 
      final CoolBar coolBar = new CoolBar(shell, SWT.BORDER);
      coolBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));  
 
      // create the first ToolBar
      ToolBar toolBar = new ToolBar(coolBar, SWT.NULL);
      ToolItem toolItem = new ToolItem(toolBar, SWT.PUSH);      
      toolItem.setImage(getImage("jpgIcon.gif"));
      toolItem = new ToolItem (toolBar, SWT.SEPARATOR);
      toolItem = new ToolItem(toolBar, SWT.PUSH);      
      toolItem.setImage(getImage("gifIcon.gif"));
      toolItem = new ToolItem (toolBar, SWT.SEPARATOR);
      toolItem = new ToolItem(toolBar, SWT.PUSH);      
      toolItem.setImage(getImage("tiffIcon.gif"));
      toolItem = new ToolItem (toolBar, SWT.SEPARATOR);
       
      CoolItem coolItem = new CoolItem(coolBar, SWT.NONE);
      Point size = toolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
      size = coolItem.computeSize(size.x, size.y);
      coolItem.setSize(size);
      coolItem.setMinimumSize(toolItem.getWidth(), size.y);
      coolItem.setControl(toolBar);
            
      // create the second ToolBar
      toolBar = new ToolBar(coolBar, SWT.BORDER);
      ToolItem item = new ToolItem (toolBar, SWT.DROP_DOWN);
      item.addSelectionListener(new DropDownSelectionListener(shell));
      item.setImage(getImage("jpgIcon.gif"));
      item = new ToolItem(toolBar, SWT.DROP_DOWN);
      item.addSelectionListener(new DropDownSelectionListener(shell));
      item.setImage(getImage("gifIcon.gif"));
      
      coolItem = new CoolItem(coolBar, SWT.NONE);
      size = toolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
      size = coolItem.computeSize(size.x, size.y);
      coolItem.setSize(size);
      coolItem.setMinimumSize(toolItem.getWidth(), size.y);
      coolItem.setControl(toolBar);
       
      // all the indices that will begin on a new row      
      coolBar.setWrapIndices(new int[] {0, 1});
 
      SelectionListener selectionListener = new SelectionAdapter () {
         public void widgetSelected(SelectionEvent event) {
            Button button = ((Button) event.widget);
            coolBar.setLocked(button.getSelection());
         };
      };
      
      Group buttonGroup = new Group(shell, SWT.NONE);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 1;
      buttonGroup.setLayout(gridLayout);
      buttonGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));      
      Button lockButton = new Button(buttonGroup, SWT.CHECK);
      lockButton.setText("Lock the CoolBar!");
      lockButton.addSelectionListener(selectionListener);
                 
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
   }
   
   public static Image getImage(String imageName) {
      ImageData source = new ImageData(Main.class.getResourceAsStream(imageName));
      ImageData mask = source.getTransparencyMask();
      Image image = new Image(null, source, mask);
      return image;
   }   
   
   
   static class DropDownSelectionListener extends SelectionAdapter {
      private Menu menu = null;
      private Shell shell;
      
      public DropDownSelectionListener(Shell shell) {
         this.shell = shell;
      }
      
      public void widgetSelected(SelectionEvent event) {
         System.out.println("Widget is clicked on!");
         if (menu == null) {
            // create menu if it doesn't exist already
            menu = new Menu(shell);
            MenuItem menuItem1 = new MenuItem(menu, SWT.NONE);
            menuItem1.setText("App #1");
            MenuItem menuItem2 = new MenuItem(menu, SWT.NONE);
            menuItem2.setText("App #2");
            MenuItem separatorItem = new MenuItem(menu, SWT.SEPARATOR);
            MenuItem menuItem3 = new MenuItem(menu, SWT.NONE);
            menuItem3.setText("Run...");
            
            menuItem1.addSelectionListener(new SelectionAdapter() {
               public void widgetSelected(SelectionEvent e) {
                  menu.setVisible(true);
               }
            });
         }
         
         // if user clicked on down arrow, show menu
         if (event.detail == SWT.ARROW) {
            System.out.println("... and it's the arrow!");
            if (menu.getVisible()) {
               menu.setVisible(false);
            } else { 
               final ToolItem toolItem = (ToolItem) event.widget;
               final ToolBar  toolBar = toolItem.getParent();
               
               Rectangle toolItemBounds = toolItem.getBounds();
               Point point = toolBar.toDisplay(new Point(toolItemBounds.x, toolItemBounds.y));
               menu.setLocation(point.x, point.y + toolItemBounds.height);
               menu.setVisible(true);
            }
         }
      }
   }   
} 

Having a border around an SWT list

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.List;
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 List Demonstration");
      shell.setLayout(new GridLayout());

      String []items = {"Belgium", "The Netherlands", "France", "Germany", "Italy",
                        "Luxembourg", "Switzerland", "Austria", "Finland", "Iceland" };
      
      // to have a border around your list, "or" SWT.BORDER
      final List list = new List(shell, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.BORDER);
      list.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
      list.setItems (items);
            
      shell.open();
      
      shell.addShellListener(new ShellAdapter() {
         public void shellClosed(ShellEvent se) {
            int[] indices = list.getSelectionIndices();
            System.out.println("Selected items:");
            for (int i=0; i<indices.length; i++) {
               System.out.println(list.getItem(indices[i]));   
            }
         }
      });      

      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      
      display.dispose();
   }
   
   public static void recurseTree(TreeItem item) {
      System.out.println(item.getText() + "tChecked=" + item.getChecked());
      TreeItem[] treeItems = item.getItems(); 
      for (int i=0; i<treeItems.length; i++) {
         TreeItem treeItem = treeItems[i];
         recurseTree(treeItem);
      }   
   }
}

Creating a multi-selection list in SWT

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.List;
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 List Demonstration");
      shell.setLayout(new GridLayout());
 
      String []items = {"Belgium", "The Netherlands", "France", "Germany", "Italy",
                        "Luxembourg", "Switzerland", "Austria", "Finland", "Iceland" };
       
      final List list = new List(shell, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI);
      list.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
      list.setItems (items);
             
      shell.open();
       
      shell.addShellListener(new ShellAdapter() {
         public void shellClosed(ShellEvent se) {
            int[] indices = list.getSelectionIndices();
            System.out.println("Selected items:");
            for (int i=0; i<indices.length; i++) {
               System.out.println(list.getItem(indices[i]));   
            }
         }
      });      
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
       
      display.dispose();
   }
    
   public static void recurseTree(TreeItem item) {
      System.out.println(item.getText() + "tChecked=" + item.getChecked());
      TreeItem[] treeItems = item.getItems(); 
      for (int i=0; i<treeItems.length; i++) {
         TreeItem treeItem = treeItems[i];
         recurseTree(treeItem);
      }   
   }
}

Creating a list in SWT

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.List;
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 List Demonstration");
      shell.setLayout(new GridLayout());
 
      String []items = {"Belgium", "The Netherlands", "France", "Germany", "Italy",
                        "Luxembourg", "Switzerland", "Austria", "Finland", "Iceland" };
       
      final List list = new List(shell, SWT.H_SCROLL | SWT.V_SCROLL);
      list.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
      list.setItems (items);
             
      shell.open();
       
      shell.addShellListener(new ShellAdapter() {
         public void shellClosed(ShellEvent se) {
            int[] indices = list.getSelectionIndices();
            System.out.println("Selected items:");
            for (int i=0; i<indices.length; i++) {
               System.out.println(list.getItem(indices[i]));   
            }
         }
      });      
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
       
      display.dispose();
   }
    
   public static void recurseTree(TreeItem item) {
      System.out.println(item.getText() + "tChecked=" + item.getChecked());
      TreeItem[] treeItems = item.getItems(); 
      for (int i=0; i<treeItems.length; i++) {
         TreeItem treeItem = treeItems[i];
         recurseTree(treeItem);
      }   
   }
}

Adding a popup listener to a JTable row

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      super("TableModel Demonstration");
 
      // create our own custom TableModel
      WineTableModel wineModel = new WineTableModel();
      final JTable table = new JTable(wineModel);
 
      // add rows to our TableModel, each row is represented as a Wine object
      wineModel.addWine(new Wine("Chateau Meyney, St. Estephe", "1994", 18.75f, true));
      wineModel.addWine(new Wine("Chateau Montrose, St. Estephe", "1975", 54.25f, true));
      wineModel.addWine(new Wine("Chateau Gloria, St. Julien", "1993", 22.99f, false));
      wineModel.addWine(new Wine("Chateau Beychevelle, St. Julien", "1970", 61.63f, false));
      wineModel.addWine(new Wine("Chateau La Tour de Mons, Margeaux", "1975", 57.03f, true));
      wineModel.addWine(new Wine("Chateau Brane-Cantenac, Margeaux", "1978", 49.92f, false));
 
      // create the scroll pane and add the table to it. 
      JScrollPane scrollPane = new JScrollPane(table);
 
      // add the scroll pane to this window.
      getContentPane().add(scrollPane, BorderLayout.CENTER);
 
      final TablePopup tablePopup = new TablePopup(table);
      table.addMouseListener(new MouseAdapter() {
         public void mouseReleased(MouseEvent me) {
            int row = table.rowAtPoint(me.getPoint());
            System.out.println("You clicked at row " + row);
            // possibly use row variable here to do something specific with your popup menu
            if (me.isPopupTrigger()) {
               tablePopup.show(me.getComponent(), me.getX(), me.getY());
            }
         }
      });
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}
 
// a simple object that holds data about a particular wine
class Wine {
   private String  name;
   private String  vintage;
   private float   price;
   private boolean inStock;
 
   public Wine(String name, String vintage, float price, boolean inStock) {
      this.name = name;
      this.vintage = vintage;
      this.price = price;
      this.inStock = inStock;
   }
 
   public String getName()     { return name; }
   public String getVintage()  { return vintage; }
   public float  getPrice()    { return price; } 
   public boolean getInStock() { return inStock; }
 
   public String toString() { 
      return "[" + name + ", " + vintage + ", " + price + ", " + inStock + "]"; }
}
 
class WineTableModel extends AbstractTableModel {
   // holds the strings to be displayed in the column headers of our table
   final String[] columnNames = {"Name", "Vintage", "Price", "In stock?"};
 
   // holds the data types for all our columns
   final Class[] columnClasses = {String.class, String.class, Float.class, Boolean.class};
 
   // holds our data
   final Vector data = new Vector();
  
   // adds a row
   public void addWine(Wine w) {
      data.addElement(w);
      fireTableRowsInserted(data.size()-1, data.size()-1);
   }
 
   public int getColumnCount() {
      return columnNames.length;
   }
         
   public int getRowCount() {
      return data.size();
   }
 
   public String getColumnName(int col) {
      return columnNames[col];
   }
 
   public Class getColumnClass(int c) {
      return columnClasses1;
   }
 
   public Object getValueAt(int row, int col) {
      Wine wine = (Wine) data.elementAt(row);
      if (col == 0)      return wine.getName();
      else if (col == 1) return wine.getVintage();
      else if (col == 2) return new Float(wine.getPrice());
      else if (col == 3) return new Boolean(wine.getInStock());
      else return null;
   }
 
   public boolean isCellEditable(int row, int col) {
      return false;
   }
}
 
class TablePopup extends JPopupMenu {
   public TablePopup(JTable tree) {
      JMenuItem itemEdit = new JMenuItem("Edit");
      JMenuItem itemDelete = new JMenuItem("Delete");
      itemEdit.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Edit child");
         }
      });
      itemDelete.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Delete selected");
         }
      });
 
      add(itemEdit);
      add(new JSeparator());
      add(itemDelete);
   }
}

Creating a checked SWT Tree

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
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.TableItem;
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 Checked Tree Demonstration");
      shell.setLayout(new GridLayout());
 
      final Tree tree = new Tree(shell, SWT.BORDER | SWT.CHECK);
        
      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();
       
      shell.addShellListener(new ShellAdapter() {
         public void shellClosed(ShellEvent se) {
            TreeItem[] treeItems = tree.getItems();
            for (int i=0; i<treeItems.length; i++) {
               recurseTree(treeItems[i]);
            }
         }
      });      
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      
      display.dispose();
   }
   
   public static void recurseTree(TreeItem item) {
      System.out.println(item.getText() + "tChecked=" + item.getChecked());
      TreeItem[] treeItems = item.getItems(); 
      for (int i=0; i<treeItems.length; i++) {
         TreeItem treeItem = treeItems[i];
         recurseTree(treeItem);
      }   
   }
}