按JTable中未包含的值对JTable进行排序

时间:2015-09-30 10:01:54

标签: java swing jtable tablerowsorter

我有一个JTable,它显示了

类型的数据数组
String [] data = {"String1", "String2", "String3", "String4"};

但是在JTable中我只显示前3个项目,第四个项目是隐藏的。但是我甚至会在JTable中没有显示的String4的基础上对表进行排序。我阅读了JTable教程,我发现了如何使用TableRowSorter并设置Comparator,但方法setComparator希望将其作为参数列,但这不适用于我。

有人可以帮我解决这个问题吗?谢谢

1 个答案:

答案 0 :(得分:3)

诀窍是,包括TableModel中的列,但将其从TableColumnModel

中删除

Sorted

" A"列实际上是随机生成的,因此它将以不可预测的方式排序

您可以使用sorter.setSortable(1, false);之类的内容禁用可排序的列,这可用于防止用户点击列标题并破坏您的隐藏"排序

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableRowSorter;

public class MagicSort {

    public static void main(String[] args) {
        new MagicSort();
    }

    public MagicSort() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private SortOrder order = SortOrder.ASCENDING;

        public TestPane() {
            RowDataTableModel model = new RowDataTableModel();
            TableRowSorter<RowDataTableModel> sorter = new TableRowSorter<>(model);
            sorter.setComparator(0, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return o1.compareTo(o2);
                }
            });

            JTable table = new JTable(model);
            table.setRowSorter(sorter);
            table.getColumnModel().removeColumn(table.getColumn("A"));

            setLayout(new BorderLayout());
            add(new JScrollPane(table));

            JButton change = new JButton("Change");
            add(change, BorderLayout.SOUTH);

            change.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    sort(sorter);
                }
            });

            sort(sorter);
        }

        protected void sort(TableRowSorter<RowDataTableModel> sorter) {

            List<RowSorter.SortKey> keys = new ArrayList<>(1);
            keys.add(new RowSorter.SortKey(0, order));

            sorter.setSortKeys(keys);

            switch (order) {
                case ASCENDING:
                    order = SortOrder.DESCENDING;
                    break;
                case DESCENDING:
                    order = SortOrder.UNSORTED;
                    break;
                case UNSORTED:
                    order = SortOrder.ASCENDING;
                    break;
            }

        }

    }

    public class RowDataTableModel extends AbstractTableModel {

        private List<RowData> data = new ArrayList<>(25);

        public RowDataTableModel() {
            for (int index = 0; index < 10; index++) {
                data.add(new RowData(index));
            }
        }

        public String getKeyColumnValue(int row) {
            return data.get(row).get(0);
        }

        @Override
        public int getRowCount() {
            return data.size();
        }

        @Override
        public int getColumnCount() {
            return 5;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return data.get(rowIndex).get(columnIndex);
        }

    }

    public class RowData {

        private List<String> values = new ArrayList<>();

        public RowData(int offset) {
            offset *= 5;
            for (int index = 1; index < 5; index++) {
                values.add(Character.toString((char) ('A' + (offset + index))));
            }

            values.add(0, Character.toString((char) ('A' + Math.random() * 26)));
        }

        public String get(int col) {
            return values.get(col);
        }

    }

}

注意:但是,从视觉上看,这可能会让用户感到困惑,所以我会谨慎使用它。