以编程方式对JTable进行排序

aur*_*amo 10 java swing

有没有办法以编程方式对JTable进行排序?

我的JTable排序工作(使用setRowSorter),这样当用户按下任何列时,表就会被排序.

我知道,SWingX JXTable可能会起作用,但我宁愿不经历麻烦,因为其他一切现在都非常有效,我不知道NetBeans的可视化编辑器如何处理JXTable等等.

编辑: 所选答案是指我(现已删除)的声明,即Sun的页面答案对我不起作用.那只是我无知造成的环境问题.

cam*_*ckr 15

对我来说很好:

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

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

        final JTable table = new JTable(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)
            {
                // Lookup first non-null data on column
                for (int row = 0; row < getRowCount(); row++) 
                {
                    Object o = getValueAt(row, column);

                    if (o != null)
                        return o.getClass();
                }

                return Object.class;
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        table.setAutoCreateRowSorter(true);
        // DefaultRowSorter has the sort() method
        DefaultRowSorter sorter = ((DefaultRowSorter)table.getRowSorter()); 
        ArrayList list = new ArrayList();
        list.add( new RowSorter.SortKey(2, SortOrder.ASCENDING) );
        sorter.setSortKeys(list);
        sorter.sort();

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

    public static void main(String[] args)
    {
        TableBasic frame = new TableBasic();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

当某些东西不起作用时,下次发布你的SSCCE.


Mat*_*ieu 5

您也可以通过调用触发行排序toggleSortOrder()RowSorter您的JTable

table.getRowSorter().toggleSortOrder(columnIndex);
Run Code Online (Sandbox Code Playgroud)

但是请注意,(引用Javadoc):

反转指定列的排序顺序。通常,如果指定的列已经是主排序列,则这将使排序顺序从升序降到降序(或降序到升序)。

虽然这样比较快,但是setSortKeys()按@camickr(向他+1)所示的呼叫是正确的方法(但是您需要实例化一个List)。