如何在Java中对jTable列进行排序

时间:2013-03-08 07:10:54

标签: java swing jtable

我通过NetBean GUI制作JTabel名称“infoTable”。有2列(A& B) 我向这个JTabel添加数据(通过GUI) 我如何对第1列或第2列中的数据进行排序。我在谷歌搜索但所有答案都不适用于我。 有人可以给我一些代码吗?感谢

2 个答案:

答案 0 :(得分:3)

好吧,不是最精彩的例子,但它得到了重点。

插入一些下降数据......

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.PopupMenu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Action;
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 static javax.swing.SortOrder.ASCENDING;
import static javax.swing.SortOrder.DESCENDING;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class TestTableSorter {

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

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

                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
                    final JTable table = new JTable();
                    DefaultTableModel model = new DefaultTableModel(
                                    new Object[][]{
                        {"A", 1, sdf.parse("12/05/2000")},
                        {"B", 2, sdf.parse("12/06/2000")},
                        {"C", 3, sdf.parse("12/07/2000")},
                        {"D", 4, sdf.parse("12/08/2000")},
                        {"E", 5, sdf.parse("12/09/2000")},
                        {"F", 1, sdf.parse("12/10/2000")},
                        {"G", 2, sdf.parse("12/11/2000")},
                        {"H", 3, sdf.parse("12/12/2000")},
                        {"I", 4, sdf.parse("12/01/1990")},
                        {"J", 5, sdf.parse("12/02/1990")},
                        {"K", 1, sdf.parse("12/03/1990")},
                        {"L", 2, sdf.parse("12/04/1995")},
                        {"M", 3, sdf.parse("12/05/1995")},
                        {"N", 4, sdf.parse("12/06/1995")},
                        {"O", 5, sdf.parse("12/07/1995")},
                        {"P", 1, sdf.parse("12/08/1980")},
                        {"Q", 2, sdf.parse("12/09/1980")},
                        {"R", 3, sdf.parse("12/10/1980")},
                        {"S", 4, sdf.parse("12/11/1980")},
                        {"T", 5, sdf.parse("12/12/1980")},
                        {"U", 1, sdf.parse("12/01/1985")},
                        {"V", 2, sdf.parse("12/02/1985")},
                        {"W", 3, sdf.parse("12/03/1985")},
                        {"X", 4, sdf.parse("12/04/1985")},
                        {"Y", 5, sdf.parse("12/05/1985")},
                        {"Z", 1, sdf.parse("12/06/1985")},},
                                    new Object[]{"Name", "Number", "Date"});

                    table.setModel(model);
                    table.setAutoCreateRowSorter(true);

                    JPanel panel = new JPanel(new GridLayout(1, 3));
                    panel.add(createButton(table, 0));
                    panel.add(createButton(table, 1));
                    panel.add(createButton(table, 2));

                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(panel, BorderLayout.NORTH);
                    frame.add(new JScrollPane(table));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (Exception exp) {
                    exp.printStackTrace();
                }
            }

            protected JButton createButton(JTable table, int col) {
                JButton btn = new JButton("");
                btn.addActionListener(new SortAction(table, col));
                return btn;
            }

        });
    }

    public class SortAction implements ActionListener {

        private JTable table;
        private int column;

        public SortAction(JTable table, int column) {
            this.table = table;
            this.column = column;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            RowSorter<? extends TableModel> rowSorter = table.getRowSorter();
            List<RowSorter.SortKey> sortKeys = new ArrayList<RowSorter.SortKey>(rowSorter.getSortKeys());
            boolean found = false;
            SortOrder order = SortOrder.ASCENDING;
            for (int index = 0; index < sortKeys.size(); index++) {
                RowSorter.SortKey key = sortKeys.get(index);
                if (key.getColumn() == column) {
                    found = true;
                    System.out.println("Found existing sort key for column " + column);
                    switch (key.getSortOrder()) {
                        case ASCENDING:
                            order = SortOrder.DESCENDING;
                            sortKeys.set(index, new RowSorter.SortKey(column, order));
                            break;
                        case DESCENDING:
                            order = SortOrder.UNSORTED;
                            sortKeys.remove(index);
                            break;
                    }
                    break;
                }
            }
            if (!found) {
                System.out.println("Add new sort key for column " + column);
                sortKeys.add(new RowSorter.SortKey(column, order));
            }
            System.out.println("List contains " + sortKeys.size());
            RowSorter newSorter = new TableRowSorter(table.getModel());
            newSorter.setSortKeys(sortKeys);
            table.setRowSorter(newSorter);
            switch (order) {
                case ASCENDING:
                    ((JButton) e.getSource()).setText("+");
                    break;
                case DESCENDING:
                    ((JButton) e.getSource()).setText("-");
                    break;
                default:
                    ((JButton) e.getSource()).setText(" ");
                    break;
            }
        }
    }
}

答案 1 :(得分:1)

使用JXTable:内置排序,扩展JTable。对JTable进行点击排序是一件非常麻烦的事情(但可以在线找到分步教程)。