Adrian Adrian - 1 year ago 95
MySQL Question

How can I sort a table by column in SWT

I'm making a program that gets data from a database in MySQL and puts it into a SWT Table and the way I was sorting the table was deleting all the TableItem's and loading all the sorted data again from the database but when there are a lot of rows in the database it takes a lot loading the data

I tried some codes that I found to sort a Table but they didn't work, I don't know if I was doing right or not but didn't work

Is there any easy way to sort a SWT Table?

Answer Source

Here you have an appropriate code example for sorting swt columns:

import org.eclipse.swt.*;  
 import org.eclipse.swt.widgets.*;  
 import org.eclipse.swt.layout.*;  
 import java.text.*;  
 import java.util.*;  

public class SortTable {  

  public static void main(String[] args) {  
     Display display = new Display ();  
     Shell shell = new Shell (display);  
     shell.setLayout(new FillLayout());  
     final Table table = new Table(shell, SWT.BORDER);  
     final TableColumn column1 = new TableColumn(table, SWT.NONE);  
     column1.setText("Column 1");  
     final TableColumn column2 = new TableColumn(table, SWT.NONE);  
     column2.setText("Column 2");  
     TableItem item = new TableItem(table, SWT.NONE);  
     item.setText(new String[] {"a", "3"});  
     item = new TableItem(table, SWT.NONE);  
     item.setText(new String[] {"b", "2"});  
     item = new TableItem(table, SWT.NONE);  
     item.setText(new String[] {"c", "1"});  
     Listener sortListener = new Listener() {  
         public void handleEvent(Event e) {  
             TableItem[] items = table.getItems();  
             Collator collator = Collator.getInstance(Locale.getDefault());  
             TableColumn column = (TableColumn)e.widget;  
             int index = column == column1 ? 0 : 1;  
             for (int i = 1; i < items.length; i++) {  
                 String value1 = items[i].getText(index);  
                 for (int j = 0; j < i; j++){  
                     String value2 = items[j].getText(index);  
                     if (, value2) < 0) {  
                         String[] values = {items[i].getText(0), items[i].getText(1)};  
                         TableItem item = new TableItem(table, SWT.NONE, j);  
                         items = table.getItems();  
     column1.addListener(SWT.Selection, sortListener);  
     column2.addListener(SWT.Selection, sortListener);  
     shell.setSize(shell.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 300);;  
     while (!shell.isDisposed ()) {  
         if (!display.readAndDispatch ()) display.sleep ();  
     display.dispose ();  

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download