How to order 1000 elements in a swt column table with O(n log(n)) complexity! using Comparator and Array.sort() implemented in a TableColumn Listener Factory : Table « SWT JFace Eclipse « Java






How to order 1000 elements in a swt column table with O(n log(n)) complexity! using Comparator and Array.sort() implemented in a TableColumn Listener Factory

How to order 1000 elements in a swt column table with O(n log(n)) complexity! using Comparator and Array.sort() implemented in a TableColumn Listener Factory


/*
 *  This snippet show how to order 1000 elements in a swt column table 
 *  with O(n log(n)) complexity! using Comparator and Array.sort() 
 *  implemented in a TableColumn Listener Factory
 *  
 *  Comparator implemented: INT_COMPARATOR, STRING_COMPARATOR, DATE_COMPARATOR, DOUBLE_COMPARATOR, HOUR_COMPARATOR  
 *  Example: column.addListener(SWT.Selection, SortListenerFactory.getListener(SortListenerFactory.STRING_COMPARATOR));
 *  
 *  Gianluigi Davassi 
 *  Feel free to contact me: davassi (at) yahoo.it
 *  
 * */

/*  Copyright (C) 2004 by Gianluigi Davassi www.omega-dream.com
 
 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
 Author: Gianluigi Davassi
 davassi (at) yahoo.it
 www.omega-dream.com
 
 */


package org.omegadream;

import java.text.Collator;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
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 TableSortListenerFactory {

    private static final int MAX_ELEMENTS = 1000;
    private Display display;
    private Shell shell;
    
    private Table table;
    private TableColumn intColumn,stringColumn,dateColumn,doubleColumn,hourColumn;  
    
    private Random ran = new Random();
    
    public TableSortListenerFactory() {
        display = new Display();
        shell = new Shell(display);

        shell.setSize(640, 480);
        
        shell.setText("A Table Sorter Example. Click on column header to order it!");
        shell.setLayout(new FillLayout());

        table = new Table(shell, SWT.HIDE_SELECTION|SWT.SINGLE|SWT.FULL_SELECTION|SWT.BORDER);
        table.setHeaderVisible(true);
        table.setLinesVisible(true);

        intColumn = new TableColumn(table, SWT.CENTER);
        intColumn.setText("Number Column");
        intColumn.setWidth(120);
        intColumn.addListener(SWT.Selection, SortListenerFactory.getListener(SortListenerFactory.INT_COMPARATOR));
        
        stringColumn = new TableColumn(table, SWT.CENTER);
        stringColumn.setText("String Column");
        stringColumn.setWidth(120);
        stringColumn.addListener(SWT.Selection, SortListenerFactory.getListener(SortListenerFactory.STRING_COMPARATOR));
        
        dateColumn = new TableColumn(table, SWT.CENTER);
        dateColumn.setText("Date Column");
        dateColumn.setWidth(120);
        dateColumn.addListener(SWT.Selection, SortListenerFactory.getListener(SortListenerFactory.DATE_COMPARATOR));
        
        doubleColumn = new TableColumn(table, SWT.CENTER);
        doubleColumn.setText("Double Column");
        doubleColumn.setWidth(120);
        doubleColumn.addListener(SWT.Selection, SortListenerFactory.getListener(SortListenerFactory.DOUBLE_COMPARATOR));
        
        hourColumn = new TableColumn(table, SWT.CENTER);
        hourColumn.setText("Hour Column");
        hourColumn.setWidth(120);
        hourColumn.addListener(SWT.Selection, SortListenerFactory.getListener(SortListenerFactory.HOUR_COMPARATOR));
     
        // let's populate the table with random data!
        for (int i = 0; i< MAX_ELEMENTS ; i++)
        {
            String int_value = String.valueOf(ran.nextInt(1000000));
            
            String string_value = randomstring(4,16);
            
            String date_value = "" + ran.nextInt(31) + "/" + ran.nextInt(12) + "/" + ran.nextInt(2000); // dd-mm-aaaa
            
            String double_value = String.valueOf(ran.nextDouble());
            
            String hour_value = "" + ran.nextInt(24) + ":" + ran.nextInt(60) + ":" + ran.nextInt(60); // hh:mm:SS
            
            // ok now store it in the table
            TableItem item = new TableItem(table, SWT.NONE);
            item.setText(new String[] { int_value, string_value, date_value, double_value, hour_value });
        }
      
        shell.open();
        while (!shell.isDisposed()) {
          if (!display.readAndDispatch())
            display.sleep();
        }
        display.dispose();
    }
    
    
    public static void main(String[] args)
    {
        new TableSortListenerFactory();
    }
    
    private int rand(int lo, int hi)
    {
            int n = hi - lo + 1;
            int i = ran.nextInt() % n;
            if (i < 0)
                    i = -i;
            return lo + i;
    }

    private String randomstring(int lo, int hi)
    {
            int n = rand(lo, hi);
            byte b[] = new byte[n];
            for (int i = 0; i < n; i++)
                    b[i] = (byte)rand('a', 'z');
            return new String(b, 0);
    }
    
}

// this is the ListenerFactory implementation

class SortListenerFactory implements Listener
{
    private Comparator currentComparator = null;
    
    private Collator col = Collator.getInstance(Locale.getDefault());
    
    public static final int INT_COMPARATOR    = 0;
    public static final int STRING_COMPARATOR = 1;
    public static final int DATE_COMPARATOR   = 2;
    public static final int DOUBLE_COMPARATOR = 3;
    public static final int HOUR_COMPARATOR   = 4;
    
    private SortListenerFactory(int _comp)
    {
        switch (_comp) 
        {
        case INT_COMPARATOR:
            currentComparator = intComparator;
            break;

        case STRING_COMPARATOR:
            currentComparator = strComparator;
            break;

        case DATE_COMPARATOR:
            currentComparator = dateComparator;
            break;
            
        case DOUBLE_COMPARATOR:
            currentComparator = doubleComparator;
            break;
            
        case HOUR_COMPARATOR:
            currentComparator = hourComparator;
            break;

        default:
            currentComparator = strComparator;
        }
    }
    
    public static Listener getListener(int _comp)
    {
        return new SortListenerFactory(_comp);
    }
    
    private int colIndex = 0;
    private int updown   = 1;
          
    // Integer Comparator
    private Comparator intComparator = new Comparator()
    {
        public int compare(Object arg0, Object arg1) {

            TableItem t1 = (TableItem)arg0;
            TableItem t2 = (TableItem)arg1;

            int v1 = Integer.parseInt(t1.getText(colIndex));
            int v2 = Integer.parseInt(t2.getText(colIndex));

            if (v1<v2) return 1*updown;
            if (v1>v2) return -1*updown;

            return 0;
        }    
    };
         
    // String Comparator
    private Comparator strComparator = new Comparator()
    {
        public int compare(Object arg0, Object arg1) {

            TableItem t1 = (TableItem)arg0;
            TableItem t2 = (TableItem)arg1;

            String v1 = (t1.getText(colIndex));
            String v2 = (t2.getText(colIndex));

            return (col.compare(v1,v2))*updown;
        }    
    };
    
    // Double Comparator
    private Comparator doubleComparator = new Comparator()
    {
        public int compare(Object arg0, Object arg1) {
            
            TableItem t1 = (TableItem)arg0;
            TableItem t2 = (TableItem)arg1;
            
            double v1 = Double.parseDouble(t1.getText(colIndex));
            double v2 = Double.parseDouble(t2.getText(colIndex));
            
            if (v1<v2) return 1*updown;
            if (v1>v2) return -1*updown;
            
            return 0;
        }    
    };
    
    // Hour Comparator (hh:mm:ss)
    private Comparator hourComparator = new Comparator()
    {
        public int compare(Object arg0, Object arg1) {
            
            TableItem t1 = (TableItem)arg0;
            TableItem t2 = (TableItem)arg1;
            
            String v1 = (t1.getText(colIndex)).trim();
            String v2 = (t2.getText(colIndex)).trim();
            
            DateFormat df = new SimpleDateFormat("hh:mm:ss");
           
            Date d1 = null; Date d2 = null;
            
            try {                
                d1 = df.parse(v1);
            } catch (ParseException e) 
            { 
                System.out.println("[WARNING] v1 " + v1);
                try { d1 = df.parse("01:01:01"); } catch (ParseException e1) {}
            }
            
            try {               
                d2 = df.parse(v2);
            } catch (ParseException e) 
            { 
                System.out.println("[WARNING] v2 " + v2);
                try { d2 = df.parse("01:01:01"); } catch (ParseException e1) {}
            }

            if (d1.equals(d2))
                return 0;

            return updown*(d1.before(d2) ? 1 : -1);
        }    
    };
    
    private Comparator dateComparator = new Comparator()
    {
        public int compare(Object arg0, Object arg1) 
        {    
            TableItem t1 = (TableItem)arg0;
            TableItem t2 = (TableItem)arg1;
            
            String v1 = (t1.getText(colIndex)).trim();
            String v2 = (t2.getText(colIndex)).trim();

            v1.replaceAll("-", "/");
            v2.replaceAll("-", "/");
            
            DateFormat df_europe = new SimpleDateFormat("dd/MM/yyyy");
            DateFormat df_usa = new SimpleDateFormat("yyyy/MM/dd");

            DateFormat df = df_europe;
            
            Date d1 = null; Date d2 = null;
            
            try {
                d1 = df.parse(v1);
            } catch (ParseException e) 
            { 
               //System.out.println("[WARNING] v1 " + v1);
                d1 = new Date("01/01/1900");
            }
            
            try {               
                d2 = df.parse(v2);
            } catch (ParseException e) 
            { 
                d2 = new Date("01/01/1900");
            }

            if (d1.equals(d2))
                return 0;

            return updown*(d1.before(d2) ? 1 : -1);
        }    
    };
        
    public void handleEvent(Event e) {
        
        updown = (updown == 1 ? -1 : 1);
        
        TableColumn currentColumn = (TableColumn)e.widget;
        Table table = currentColumn.getParent();
    
        colIndex = searchColumnIndex(currentColumn);
        
        table.setRedraw(false);
        
        TableItem[] items = table.getItems();
       
        Arrays.sort(items,currentComparator);
        
        table.setItemCount(items.length);
        
        for (int i = 0;i<items.length;i++)
        {   
            TableItem item = new TableItem(table,SWT.NONE,i);
            item.setText(getData(items[i]));
            items[i].dispose();
        }
        
        table.setRedraw(true);     
    }
    
    private String[] getData(TableItem t)
    {
        Table table = t.getParent();
        
        int colCount = table.getColumnCount();
        String [] s = new String[colCount];
        
        for (int i = 0;i<colCount;i++)
            s[i] = t.getText(i);
                
        return s;
        
    }
    
    private int searchColumnIndex(TableColumn currentColumn)
    {
        Table table = currentColumn.getParent();
        
        int in = 0;
        
        for (int i = 0;i<table.getColumnCount();i++)
            if (table.getColumn(i) == currentColumn)
                in = i;
        
        return in;
    }
}

           
       








Related examples in the same category

1.Print KTable (SWT Table)Example Print KTable (SWT Table)Example
2.The source of a custom table class for Java SWT applicationsThe source of a custom table class for Java SWT applications
3.SWT Table Editor
4.Simple File Browser in SWT TableSimple File Browser in SWT Table
5.Bug Tracker JFaceBug Tracker JFace
6.Bug TrackerBug Tracker
7.File Browser DemoFile Browser Demo
8.TableEditor exampleTableEditor example
9.File Browser SampleFile Browser Sample
10.File Browser JFace
11.Bug ReportBug Report
12.Displays ASCII CodesDisplays ASCII Codes
13.Demonstrates the SWT.VIRTUAL styleDemonstrates the SWT.VIRTUAL style
14.Displays a tableDisplays a table
15.A table of baseball players and allows sortingA table of baseball players and allows sorting
16.Demonstrates TableCursorDemonstrates TableCursor
17.Demonstrates TableTreeDemonstrates TableTree
18.Demonstrates TableEditorDemonstrates TableEditor
19.Shows the extensions on the system and their associated programsShows the extensions on the system and their associated programs
20.Table Example 3Table Example 3
21.Table Example 2Table Example 2
22.Table ExampleTable Example
23.Demonstrates TableViewersDemonstrates TableViewers
24.Demonstrates CheckboxTableViewerDemonstrates CheckboxTableViewer
25.Demonstrates CellEditorsDemonstrates CellEditors
26.SWT Table Simple DemoSWT Table Simple Demo
27.Create fake tooltips for items in a SWT tableCreate fake tooltips for items in a SWT table
28.Place a progress bar in a SWT tablePlace a progress bar in a SWT table
29.edit a cell in a SWT table (in place, fancy)edit a cell in a SWT table (in place, fancy)
30.edit the text of a SWT table item (in place)edit the text of a SWT table item (in place)
31.navigate a SWT table cells with arrow keysnavigate a SWT table cells with arrow keys
32.Update SWT table item textUpdate SWT table item text
33.Sort a SWT table by columnSort a SWT table by column
34.Select an index (select and scroll) in a SWT tableSelect an index (select and scroll) in a SWT table
35.Scroll a SWT table (set the top index)Scroll a SWT table (set the top index)
36.Resize columns as SWT table resizesResize columns as SWT table resizes
37.Remove selected items in a SWT tableRemove selected items in a SWT table
38.Print selected items in a SWT tablePrint selected items in a SWT table
39.Place arbitrary controls in a SWT tablePlace arbitrary controls in a SWT table
40.Reorder columns and reorder columns programmaticallyReorder columns and reorder columns programmatically
41.Insert a SWT table column (at an index)Insert a SWT table column (at an index)
42.Insert a SWT table item (at an index)Insert a SWT table item (at an index)
43.Find a SWT table cell from mouse down (works for any table style)Find a SWT table cell from mouse down (works for any table style)
44.Find a table cell from mouse down (SWT.FULL_SELECTION)Find a table cell from mouse down (SWT.FULL_SELECTION)
45.Detect a selection or check event in a table (SWT.CHECK)Detect a selection or check event in a table (SWT.CHECK)
46.Create a SWT table with 1,000,000 itemsCreate a SWT table with 1,000,000 items
47.Create a SWT table (columns, headers, lines)Create a SWT table (columns, headers, lines)
48.Create a SWT table (no columns, no headers)Create a SWT table (no columns, no headers)
49.Color cells and rows in SWT tableColor cells and rows in SWT table
50.Create a virtual SWT table and add 1000 entries to it every 500 msCreate a virtual SWT table and add 1000 entries to it every 500 ms
51.Dropped data type depends on target item in tableDropped data type depends on target item in table
52.Create a table (lazy)Create a table (lazy)