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,344 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 92

Accepted Solution

by:
objects earned 500 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

The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

Question has a verified solution.

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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

688 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