开发者

Sorting JTable programmatically

Is there a way to sort a JTable programmatically?

I have my JTable's sort working (with setRowSorter) so that when the user presses any of the columns, the table gets sorted.

I know, SWingX JXTable would probably work, but I'd rather not go through the hassle because everything else is pretty much working now and I don't know how well NetBeans' visual editor handles JXTable etc.

EDIT: The selected answer is referring to my (now removed) statement that the answer from Sun's p开发者_运维问答ages didn't work for me. That was just an environment issue caused by my ignorance.


Works fine for me:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableBasic extends JPanel
{
    public TableBasic()
    {
        String[] columnNames = {"Date", "String", "Integer", "Boolean"};
        Object[][] data =
        {
            {new Date(), "A", Integer.valueOf(1), Boolean.TRUE },
            {new Date(), "B", Integer.valueOf(2), Boolean.FALSE},
            {new Date(), "C", Integer.valueOf(19), Boolean.TRUE },
            {new Date(), "D", Integer.valueOf(4), Boolean.FALSE}
        };

        DefaultTableModel model = new DefaultTableModel(data, columnNames)
        {
            //  Returning the Class of each column will allow different
            //  renderers and editors to be used based on Class

            public Class getColumnClass(int column)
            {
                switch (column)
                {
                    case 0: return Date.class;
                    case 2: return Integer.class;
                    case 3: return Boolean.class;
                }

                return super.getColumnClass(column);
            }
        };


        JTable table = new JTable(model);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        table.setAutoCreateRowSorter(true);

        // DefaultRowSorter has the sort() method

        ArrayList<RowSorter.SortKey> list = new ArrayList<>();
        DefaultRowSorter sorter = ((DefaultRowSorter)table.getRowSorter());
        sorter.setSortsOnUpdates(true);
        list.add( new RowSorter.SortKey(2, SortOrder.ASCENDING) );
        sorter.setSortKeys(list);
        sorter.sort();

        JScrollPane scrollPane = new JScrollPane( table );
        add( scrollPane );
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("Table Basic");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new TableBasic());
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        SwingUtilities.invokeLater( () -> createAndShowGUI() );
    }
}

Next time post your minimal, reproducible example when something doesn't work.


You also can trigger row sorting by calling toggleSortOrder() on the RowSorter of your JTable:

table.getRowSorter().toggleSortOrder(columnIndex);

Note, however, that (quoting the Javadoc):

Reverses the sort order of the specified column. Typically this will reverse the sort order from ascending to descending (or descending to ascending) if the specified column is already the primary sorted column.

Though it is quicker, calling setSortKeys() as shown by @camickr (+1 to him) is the correct way to go (but you need to instanciate a List).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜