tags:

views:

190

answers:

1

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 pages didn't work for me. That was just an environment issue caused by my ignorance.

+2  A: 

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 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)
      {
       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 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);
    }
}

Next time post your SSCCE when something doesn't work.

camickr
You are right, I had issues with my environment and was not using the latest classes from Java-side (I'm doing half Clojure/half Java-project).
auramo