?
Solved

Is there a Java Class that extends DefaultTableModel for a JTable component that implements sorting and displays sort arrow icons?

Posted on 2006-11-04
2
Medium Priority
?
2,440 Views
Last Modified: 2013-11-23
Is there a Java Class that extends DefaultTableModel for a JTable component that implements sorting and displays sort arrow icons in the column header?  The class I have that extends DefaultTableModel sorts but does not display the sort arrow icon in the column header.  Also it does not sort numbers correctly.  It sorts numbers like strings instead of numbers.

Here is the code for the class I am currently using:

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

public class SortableTableModel extends DefaultTableModel {
  JTable table;
  JTableHeader header;
  Vector columnNames;
  int selectedHeaderColumn;
  int columnCount;
  int[] minWidth;
  TableCellRenderer[] cellRenderer;
  int clickCount = 0;

  public SortableTableModel( JTable table, String[] columnNames, int rowCount ){
    super( columnNames, rowCount );
    this.table = table;
    header = table.getTableHeader();
    header.setReorderingAllowed(false);
    header.addMouseListener( new HeaderMouseAdapter() );
    this.columnNames = DefaultTableModel.convertToVector( columnNames );
    columnCount = columnNames.length;
    minWidth = new int[ columnCount ];
    cellRenderer = new TableCellRenderer[ columnCount ];
  }

  class HeaderMouseAdapter extends MouseAdapter {
    public void mousePressed( MouseEvent e ){
      Point mousePoint = new Point( e.getX(), e.getY() );
      selectedHeaderColumn = header.columnAtPoint( mousePoint );
      DefaultTableColumnModel cmodel = (DefaultTableColumnModel)table.getColumnModel();
      backupTableColumnAttr( cmodel );

      clickCount++;
      boolean reverseOrder = false;
      if( ( clickCount %2 )==0 ) reverseOrder = true;
      sort( reverseOrder );

      restoreTableColumnAttr( cmodel );
    }
    void backupTableColumnAttr( DefaultTableColumnModel cmodel ){
      for( int i=0 ; i< columnCount ; i++ ){
        TableColumn column = cmodel.getColumn(i);
        minWidth[i] = column.getMinWidth();
        cellRenderer[i] = column.getCellRenderer();
      }
    }
    void restoreTableColumnAttr( DefaultTableColumnModel cmodel ){
      for( int i=0 ; i< columnCount ; i++ ){
        TableColumn column = cmodel.getColumn(i);
        column.setMinWidth( minWidth[i] );
        column.setCellRenderer( cellRenderer[i] );
      }
    }
  }

  void sort( boolean reverseOrder ){
    Vector vec = getDataVector();
    Object[] array = vec.toArray();
    Arrays.sort( array, new Compare( selectedHeaderColumn, reverseOrder ) );
    vec = DefaultTableModel.convertToVector( array );
    setDataVector( vec, columnNames );
  }

  class Compare implements Comparator {
    int sortKey;
    boolean reverseOrder;
    Compare( int sortKey, boolean reverseOrder ){
      this.sortKey = sortKey;
      this.reverseOrder = reverseOrder;
    }
    public int compare( Object o1, Object o2 ){
      Vector v1 = (Vector)o1;
      Vector v2 = (Vector)o2;
      Comparable s1 = (Comparable)v1.get( sortKey );
      Comparable s2 = (Comparable)v2.get( sortKey );
      int ans = s1.compareTo( s2 );
      if( reverseOrder ) ans *= -1;
      return( ans );
    }
    public boolean equals( Object obj ){
      return( false );
    }

  }
}

Thank You,
Dave
0
Comment
Question by:gdkinney_2
2 Comments
 
LVL 92

Accepted Solution

by:
objects earned 2000 total points
ID: 17875098
0
 

Author Comment

by:gdkinney_2
ID: 17875875
I tried using that using TableSorter.java and TableSorterDemo.java.  The TableSorter class and the inner class MyTableModel in TableSorterDemo both extend AbstractTableModel and not DefaultTableModel.  DefaultTableModel gives me methods like addRow(Vector) and others I need.  Also the inner class MyTableModel populates the columns and data for the JTable as member variables right from the start which I don't want.  I need to change the data in my JTable by adding and deleting rows in response to user actions.  At the same time I need the sorting and column arrow icons that the TableSorter and TableSorterDemo classes provide.

I tried changing MyTableModel and TableSorter to extend DefaultTableModel instead of AbstractTableModel.  I then tried to use the classes by changing the code in the TableModelDemo constructor as follows:

    public TableSorterDemo() {
       super(new GridLayout(1,0));
       TableSorter sorter = new TableSorter();
       JTable table = new JTable(sorter); //NEW
       sorter.setTableHeader(table.getTableHeader()); //ADDED THIS
       table.setPreferredScrollableViewportSize(new Dimension(500, 70));
       //Set up tool tips for column headers.
       table.getTableHeader().setToolTipText( "Click to specify sorting; Control-Click  to specify second ary sorting");
       //Create the scroll pane and add the table to it.
       JScrollPane scrollPane = new JScrollPane(table);
       //Add the scroll pane to this panel.
       add(scrollPane);
       sorter.addColumn("First Name");
       sorter.addColumn("Last Name");
       sorter.addColumn("Address");
       sorter.addColumn("City");
       sorter.addColumn("State");
       sorter.addColumn("Zip");
       Vector myVector = new Vector();
       myVector.add("Rick");
       myVector.add("Smith");
       myVector.add("100 Main Street");
       myVector.add("New York");
       myVector.add("New York");
       myVector.add("10017");
       sorter.addRow(myVector);
    }

When I compiled and ran it I got an ArrayIndexOutOfBoundsException when I tried to add the Vector to the TableSorter on the last line of the constructor.

Please help,
Dave
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Suggested Courses
Course of the Month15 days, 8 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question