001 /*
002 * Copyright 2002-2004 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
005 * use this file except in compliance with the License. You may obtain a copy of
006 * the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
012 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
013 * License for the specific language governing permissions and limitations under
014 * the License.
015 */
016 package org.springframework.richclient.table;
017
018 import java.util.Observable;
019 import java.util.Observer;
020
021 import javax.swing.JTable;
022
023 import org.springframework.richclient.command.ActionCommand;
024 import org.springframework.richclient.progress.BusyIndicator;
025 import org.springframework.util.Assert;
026
027 /**
028 * Listens to a sort list for changes and when they happen, sorts a sortable
029 * table model in a separate worker thread.
030 *
031 * @author Keith Donald
032 */
033 public class SortTableCommand extends ActionCommand implements Observer {
034 private JTable table;
035
036 private SortableTableModel sortableTableModel;
037
038 private ColumnSortList sortList;
039
040 public SortTableCommand(JTable table, ColumnSortList sortList) {
041 super("sortCommand");
042 this.table = table;
043 Assert
044 .isTrue((table.getModel() instanceof SortableTableModel),
045 "The specified table's model must be sortable!");
046 this.sortableTableModel = (SortableTableModel)table.getModel();
047 this.sortList = sortList;
048 this.sortList.addObserver(this);
049 }
050
051 public void update(Observable o, Object args) {
052 doSort();
053 }
054
055 protected void doExecuteCommand() {
056 doSort();
057 }
058
059 private void doSort() {
060 try {
061 BusyIndicator.showAt(table);
062
063 final int[] preSortSelectedRows = table.getSelectedRows();
064
065 int[] postSortSelectedRows = sortableTableModel
066 .sortByColumns(sortList.getSortLevels(), preSortSelectedRows);
067
068 for (int i = 0; i < postSortSelectedRows.length; i++) {
069 table.addRowSelectionInterval(postSortSelectedRows[i], postSortSelectedRows[i]);
070 }
071
072 if (postSortSelectedRows.length > 0) {
073 TableUtils.scrollToRow(table, postSortSelectedRows[0]);
074 }
075 }
076 finally {
077 BusyIndicator.clearAt(table);
078 }
079 }
080
081 public void dispose() {
082 this.sortList.deleteObserver(this);
083 }
084 }