Samples > テーブルで並べ替えを実装する |
|
テーブルで並べ替えを実装するSWTのTableクラスを使ってセルの並べ替えを行うのは、少し厄介です。Tableにはもともとソートの機能が用意されていないので、自分で実装する必要があります。下のサンプルプログラムではTableColumnにSelectionListenerを追加し、カラムがクリックされたときに並べ替えの処理を行っています。並べ替えの処理は、TableItemの配列をgetItems()で取り出し、ソートに別に用意した配列に格納します。それをArraysクラスのソートメソッドで並べかえ、その結果を再びテーブルのTableItemとして格納しています。結局のところテーブルを始めから作るのと同じ事をしているわけで、あまりかっこいい実装方法ではありません。実は、JFaceのライブラリにはもっとスマートなやり方でソートを行うテーブルのフレームワークがあります。より複雑で汎用的な並べ替えを実装する場合は、JFaceのライブラリを使うほうが賢明でしょう。 スクリーンショットソースコード (TableSortTest.java)import java.util.Arrays; import java.util.Comparator; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; public class TableSortTest implements SelectionListener { private Table table; private TableColumn col2; private TableColumn col1; public static void main(String[] args) { new TableSortTest(); } public TableSortTest() { Display display = new Display(); Shell shell = new Shell(display); shell.setText("TableSortTest"); shell.setLayout(new FillLayout()); table = new Table(shell, SWT.BORDER); table.setHeaderVisible(true); col1 = new TableColumn(table, SWT.LEFT); col1.setText("Col1"); col1.setWidth(50); col2 = new TableColumn(table, SWT.LEFT); col2.setText("Col2"); col2.setWidth(50); TableItem item; //行に対応したテーブルアイテムを追加 item = new TableItem(table, SWT.NONE); item.setText(new String [] {"abc", "あ"}); item = new TableItem(table, SWT.NONE); item.setText(new String [] {"xyz", "い"}); item = new TableItem(table, SWT.NONE); item.setText(new String [] {"hij", "う"}); col1.addSelectionListener(this); col2.addSelectionListener(this); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } display.dispose(); } public void widgetSelected(SelectionEvent e) { final int colIndex; if (e.getSource() == col1){ colIndex = 0; }else if (e.getSource() == col2){ colIndex = 1; }else{ return; } TableItem[] items = table.getItems(); Object [] array = new Object[items.length]; for (int i=0; i<items.length; i++){ array[i] = new String[] {items[i].getText(0), items[i].getText(1)}; } Arrays.sort(array, new Comparator(){ public int compare(Object o1, Object o2) { String s1 = ((String[])o1)[colIndex]; String s2 = ((String[])o2)[colIndex]; return s1.compareTo(s2); } public boolean equals(Object arg0) { return false; } }); for (int i=0; i<items.length; i++){ items[i].dispose(); items[i] = new TableItem(table, SWT.NONE); String [] strs = (String[])array[i]; items[i].setText(strs); } table.redraw(); } public void widgetDefaultSelected(SelectionEvent e) { } } 参考
最新更新日: 2004年8月28日 |
- PR -
マイクロソフト お得な見積! まとめての購入ならオトクな方法で。ライセンスだから管理も簡単。 シマンテック 割引価格! オンライン販売だから低価格。いつでも簡単、見積・購入。 |
||||
|
|||||
Copyright(C) 2003,2004 Jasmin Project. All Right Reserved. |
SEO | [PR] 爆速!無料ブログ 無料ホームページ開設 無料ライブ放送 | ||