This week's book giveaway is in the Spring forum.
We're giving away four copies of Modern frontends with htmx and have Wim Deblauwe on-line!
See this thread for details.
Win a copy of Modern frontends with htmx this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Sorting the Rows in a JTable Component Based on a Column

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ranchers..would like to have your valuable help and suggestion..i am using jdk1.4.i have jtbale and would like to have one column data in sorted way..i don't want any other columns need to be done any thing.
just i am enclosing my code in tha i am using Collections.sort(data, new ColumnSorter(colIndex, ascending)); but that compare of that comparator is not at woring that data is not getting soretd.


Main java file:

/*
* Created on Jun 19, 2008
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package com.ibm.sort;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class SimpleTableDemo extends JPanel {
private boolean DEBUG = false;
int colIndex;
boolean ascending;
DefaultTableModel model = new DefaultTableModel();
public SimpleTableDemo() {
super(new GridLayout(1,0));

String[] columnNames = {"First Name","Last Name","Sport","# of Years","Vegetarian"};

Object[][] data = {
{"Mary", "Campione","Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath","Knitting", new Integer(2), new Boolean(false)},
{"Sharon", "Zakhour","Speed reading", new Integer(20), new Boolean(true)},
{"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)}
};

final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 80));
table.setAutoCreateColumnsFromModel(false);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);

sortAllRowsBy(model, 1, true);
}

public void sortAllRowsBy(DefaultTableModel model, int colIndex, boolean ascending) {
Vector data = model.getDataVector();

System.out.println("SimpleTableDemo.sortAllRowsBy()11111");

Collections.sort(data, new ColumnSorter(colIndex, ascending));
//Collections.sort(data);


//Arrays.sort(data, new ColumnSorter(colIndex, ascending));
System.out.println("SimpleTableDemo.sortAllRowsBy()2222");
model.fireTableStructureChanged();
}





/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SimpleTableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.
SimpleTableDemo newContentPane = new SimpleTableDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);

//Display the window.
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}




}




*************

Second FIle which has sorting :

/*
* Created on Jun 21, 2008
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package com.ibm.sort;

import java.util.Comparator;
import java.util.Vector;

// This comparator is used to sort vectors of data
public class ColumnSorter implements Comparator {
int colIndex;
boolean ascending;
ColumnSorter(int colIndex, boolean ascending) {
System.out.println("ColumnSorter.ColumnSorter(---colIndex--:"+colIndex+" ,ascending: "+ascending);

this.colIndex = colIndex;
this.ascending = ascending;
System.out.println("ColumnSorter.ColumnSorter()");
}
public int compare(Object a, Object b) {
System.out.println("compare-----:");
Vector v1 = (Vector)a;
Vector v2 = (Vector)b;
Object o1 = v1.get(colIndex);
Object o2 = v2.get(colIndex);
System.out.println("ColumnSorter.compare(): -o1- :"+o1+" ,o2: "+o2);
// Treat empty strains like nulls
if (o1 instanceof String && ((String)o1).length() == 0) {
o1 = null;
}
if (o2 instanceof String && ((String)o2).length() == 0) {
o2 = null;
}

// Sort nulls so they appear last, regardless
// of sort order
if (o1 == null && o2 == null) {
return 0;
} else if (o1 == null) {
return 1;
} else if (o2 == null) {
return -1;
} else if (o1 instanceof Comparable) {
if (ascending) {
System.out.println("ascending-->ColumnSorter.compare()-((Comparable)o1).compareTo(o2): "+(((Comparable)o1).compareTo(o2)));
return ((Comparable)o1).compareTo(o2);
} else {
System.out.println("Desending-->ColumnSorter.compare()-((Comparable)o1).compareTo(o2): "+(((Comparable)o1).compareTo(o2)));
return ((Comparable)o2).compareTo(o1);
}
} else {
if (ascending) {
System.out.println("ColumnSorter.compare()---o1.toString().compareTo(o2.toString())---: "+(o1.toString().compareTo(o2.toString())));
return o1.toString().compareTo(o2.toString());
} else {
return o2.toString().compareTo(o1.toString());
}
}
}
}


Please help is deadly needed.
thanks in advance!!!
 
Bartender
Posts: 5167
11
Netbeans IDE Opera Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
http://forum.java.sun.com/thread.jspa?threadID=5307390
 
Marshal
Posts: 79082
376
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by venkat anand:
Please help is deadly needed.

Ease Up, and, as Darryl has implied, it is only polite to inform people if you are posting on Other Sites.
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
call sortAllRowsBy method....pass table model,the column by which you want to sort and (ascending or descending) as parameters
you will get all rows of jtable sorted based on given column values ......

public void sortAllRowsBy(DefaultTableModel model, int colIndex, boolean ascending) {
Vector data = model.getDataVector();
Collections.sort(data, new ColumnSorter(colIndex, ascending));
model.fireTableStructureChanged();
}

public class ColumnSorter implements Comparator {
int colIndex;
boolean ascending;
ColumnSorter(int colIndex, boolean ascending) {
this.colIndex = colIndex;
this.ascending = ascending;
}
public int compare(Object a, Object b) {
Vector v1 = (Vector)a;
Vector v2 = (Vector)b;
Object o1 = v1.get(colIndex);
Object o2 = v2.get(colIndex);

// Treat empty strains like nulls
if (o1 instanceof String && ((String)o1).length() == 0) {
o1 = null;
}
if (o2 instanceof String && ((String)o2).length() == 0) {
o2 = null;
}

// Sort nulls so they appear last, regardless
// of sort order
if (o1 == null && o2 == null) {
return 0;
} else if (o1 == null) {
return 1;
} else if (o2 == null) {
return -1;
} else if (o1 instanceof Comparable) {
if (ascending) {
return ((Comparable)o1).compareTo(o2);
} else {
return ((Comparable)o2).compareTo(o1);
}
} else {
if (ascending) {
return o1.toString().compareTo(o2.toString());
} else {
return o2.toString().compareTo(o1.toString());
}
}
}
}
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic