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
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,289 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
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Protect jar file - windows app 2 65
How to convert from xls to xlsx using java 7 55
ejb entity bean example issue 2 16
Bot application - advice 3 37
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

809 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