1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 package org.apache.geronimo.st.ui; 18 19 import java.text.Collator; 20 import java.util.Locale; 21 22 import org.eclipse.swt.SWT; 23 import org.eclipse.swt.widgets.Event; 24 import org.eclipse.swt.widgets.Listener; 25 import org.eclipse.swt.widgets.Table; 26 import org.eclipse.swt.widgets.TableColumn; 27 import org.eclipse.swt.widgets.TableItem; 28 29 /** 30 * @version $Rev: 688452 $ $Date: 2008-08-24 13:56:20 +0800 (Sun, 24 Aug 2008) $ 31 * 32 * "sort a table by column" snippet from http://www.eclipse.org/swt/snippets/ 33 * 34 */ 35 public class SortListener implements Listener { 36 protected Table table; 37 protected String[] columnNames; 38 39 public SortListener(Table table, String[] columnNames) { 40 this.table = table; 41 this.columnNames = columnNames; 42 } 43 44 public void handleEvent(Event e) { 45 TableItem[] tableItems = table.getItems(); 46 Collator collator = Collator.getInstance(Locale.getDefault()); 47 TableColumn column = (TableColumn) e.widget; 48 int columnIndex = 0; 49 int direction = 0; 50 for (int i = 0; i < columnNames.length; ++i) { 51 if (column.getText().equals(columnNames[i])) { 52 table.setSortColumn(column); 53 direction = table.getSortDirection() == SWT.UP ? SWT.DOWN : SWT.UP; 54 table.setSortDirection(direction); 55 columnIndex = i; 56 break; 57 } 58 } 59 // sort the table using bubble sort technique 60 for (int i = 1; i < tableItems.length; i++) { 61 String value1 = tableItems[i].getText(columnIndex); 62 for (int j = 0; j < i; j++) { 63 String value2 = tableItems[j].getText(columnIndex); 64 boolean notSorted = false; 65 if (direction == SWT.UP && collator.compare(value1, value2) > 0) { 66 notSorted = true; 67 } 68 if (direction == SWT.DOWN && collator.compare(value1, value2) < 0) { 69 notSorted = true; 70 } 71 if (notSorted) { 72 String[] values = new String[columnNames.length]; 73 for (int col = 0; col < columnNames.length; ++col) { 74 values[col] = tableItems[i].getText(col); 75 } 76 tableItems[i].dispose(); 77 TableItem item = new TableItem(table, SWT.NONE, j); 78 item.setText(values); 79 tableItems = table.getItems(); 80 break; 81 } 82 } 83 } 84 } 85 }