[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
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,401 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 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

Enroll in October's Free Course of the Month

Do you work with and analyze data? Enroll in October's Course of the Month for 7+ hours of SQL training, allowing you to quickly and efficiently store or retrieve data. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

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

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

649 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