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
2,232 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 500 total points
Comment Utility
0
 

Author Comment

by:gdkinney_2
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
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…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

771 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now