Sorting the Rows in a JTable Component Based on a Column

Hi Masters..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...
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.
here data is the jtable complete data.
Main java file:
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!!!

Learn to use code tags.
Learn to use google.
http://www.google.com/search?q=java+sort+rows+jtable&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

Similar Messages

  • How to clear the rows in a jTable

    Can anyone tell me how to clear the contents of all the rows in a jTable?

    This is how I did. Posting the same.
    jTable1.selectAll();
    int[] array = jTable1.getSelectedRows();
    for(int i=array.length-1;i>=0;i--)
    DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
    model.removeRow(i);
    Regards.

  • How do you make the rows in a JTable uneditable.

    Hi
    Does anyone knows how to make the rows in a JTable uneditable.
    --kirk                                                                                                                                                                                   

    Hi,
    implement a TableModel, e.g AbstractTableModel and use it to initialise
    your table. (JTable aTable = new JTable(myAbstractTableModel))
    And if you want your table to be editable implement isCellEditable() in your table model, and let it return true. If not let it return false, or don't implement it att all.

  • Filtering the rows of a JTable based on JCombobox selection

    Hi,,,
    I write an application where I have a combobox contains the JTable first column data when i click on the item it should give me the rows, which contains the selected item as their first column data. I am enable to get the list like that, please, help me in this.........................................
    Thanks In Advance,
    Sun_sgrk

    Hi Albert,
    I write the code like this.............., please, check it, if I am following any where wrong let me know.......
         JComboBox filterCb=(JComboBox)evt.getSource();
            if(filterCb==filterComboBox){
                for(int i=0;i<wtOb.length;i++){
                    for(int j=0;j<4;j++){
                        if(wtOb[0].toString()==filterComboBox.getSelectedItem())
    System.out.println(""+wtOb[i][j]);
    This code I written in netbeans, when I am printing the values of wtOb[i][j] in console its getting the rows, suppose I am selecting the topic as GeneralTopic then its givining me the output as-----
    GeneralTopic
    Dealer5
    Player3
    BlackJack2
    GeneralTopic
    Dealer7
    Player6
    BlackJack
    but I am getting the trouble when i want to show these rows only in my table, please, give me any suggestion or any help to resolve it. I tried with table.setModel also but its not working.
    Regards,
    sun_sgrk

  • Setting colors of the rows of  a JTable

    Hi,
    How can we set multiple colors(foreground) for multiple rows in a JTable?. (i want to set the color of the row depends on the value of a column. Foe example if the value of a particular column is "x" then i want to set the color of that particular row as "RED" or if the value of that column is "y" then i want to set the color of the column as "GREEN". )

    Try this:
    * Method to set custom cell renderer
    *Adopted from
    * http://javaalmanac.com/egs/javax.swing.table/Stripe.html
    JTable theTable = new JTable() {
    public Component prepareRenderer(TableCellRenderer renderer,
    int row, int col) {
    Component c = super.prepareRenderer(renderer, row, col);
    //Example assumes the column number is 1 and value is "Critical"
    if (theTable.getValueAt(row, 1) != null) {
    if (theTable.getValueAt(row, 1).equals("Critical")) {
    if (col == 1) {
    c.setForeground(Color.red);
    c.setBackground(new Color(255, 255, 204));
    c.setFont(new java.awt.Font("MS Sans Serif", 1, 11));
    return c;
    };

  • Count the rows in a list-component

    Hi,
    How can I count the rows with a value in a list component?
    I thought it would be RowCount but as I figured out that shows the number of shown rows, not the number of rows with a value.

    Hi,
    Try list.dataProvider.length

  • Sort the rows of a datagridview but not the last two

    Hi,
    with this code, the last row isn't sorted:
    Protected Overrides Sub OnSortCompare(ByVal e As System.Windows.Forms.DataGridViewSortCompareEventArgs)
    MyBase.OnSortCompare(e)
    If e.RowIndex1 = Me.RowCount - 1 Then e.Handled = True
    If e.RowIndex2 = Me.RowCount - 1 Then e.Handled = True
    End Sub
    How can I expand this code to do not sort the second last row too?
    This doesn't work:
    Protected Overrides Sub OnSortCompare(ByVal e As System.Windows.Forms.DataGridViewSortCompareEventArgs)
    MyBase.OnSortCompare(e)
    If e.RowIndex1 = Me.RowCount - 1 Then e.Handled = True
    If e.RowIndex2 = Me.RowCount - 1 Then e.Handled = True
    If e.RowIndex1 = Me.RowCount - 2 Then e.Handled = True
    If e.RowIndex2 = Me.RowCount - 2 Then e.Handled = True
    End Sub

    Hi DerStauner,
    I have no idea about what do you mean “But I would like to fix the last two row”.
     My code seems sort correct all of the data in the datagridview. Would you like to share a sample about this?
    Please pay attention that the sort method of ID is according to the string, so”10” will be before than “2”. If you want to compare the ID as integer, you need to change to your code to compare with integer instead of string.
    Here is a sample (change the OnSortCompare method with following code):
    Protected Overrides Sub OnSortCompare(ByVal e As System.Windows.Forms.DataGridViewSortCompareEventArgs)
    MyBase.OnSortCompare(e)
    'If e.RowIndex1 = Me.RowCount - 1 Then e.Handled = True
    Dim a As Integer = CInt(e.CellValue1.ToString())
    Dim b As Integer = CInt(e.CellValue2.ToString())
    e.SortResult = a.CompareTo(b)
    e.Handled = True
    If e.RowIndex2 = Me.RowCount - 1 Then e.Handled = True
    End Sub
    Hope this helps.
    Mark Liu-lxf [MSFT]
    MSDN Community Support | Feedback to us

  • Highlighting a ROw in a tablular form based on a column in the row

    I have a tabular form that Has two types of records. If flightLogType = 1 then I want to highlight the row. If flightLogType=0 then no highlight. Does anyone know how to do this.

    Hi,
    I did example
    http://apex.oracle.com/pls/otn/f?p=40323:57
    Report select is just
    SELECT * FROM empI did copy my favorite report template to new name.
    Then I did edit Column Templates.
    I did set Column Template 1 conditionally "Use Based on PL/SQL expression".
    Column Template 1 Expression
    #DEPTNO# != 10To Column Template 2 I did copy what is in Template 1 and add style="background:red"Column Template 2
    <td #ALIGNMENT# headers="#COLUMN_HEADER#" class="t14data" style="background:red">#COLUMN_VALUE#</td>Column Template 2 Condition "Use Based on PL/SQL expression"
    Template 2 Expression
    #DEPTNO# = 10Then I did change report use new template
    This might help also
    http://download.oracle.com/docs/cd/E14373_01/appdev.32/e11838/themes.htm#sthref1772
    Br,Jari
    Edited by: jarola on May 11, 2010 11:24 PM

  • How to display all the rows in a JTable ???

    Hi,
    i want to display blank lines in a JTable if there is not enough rows to fill in it. For the moment, there is nothing in the JTable if i have nothing in my tables. Where am i wrong ??
    Thanks !!

    hi,
    use a contructor for jtable with the parameter rowcount or
    define a tablemodel class extends from abstract tablemodel mit the method int getRowCount()
    { return xxx;}
    table.setModel(mymodel);

  • How do you hide columns and rows in a JTable component?

    hi
    i have jTable
    basically it should contain 5 columns
    but initially i would like to show 2 and on some action performed i would like to add the other 3
    any suggestions

    Hi,
    See the TableColumnModel API for the answers you require.
    addColumn/removeColumn/moveColumn methods.
    Hope this helps for now.
    A Swing FAQ containing more comprehensive explainations of common questions - coming soon!
    Regards,
    Matt.
    Java Developer Technical Support
    Sun Microsystems
    http://www.sun.com/developers/support/

  • Displaying the Row and Column number in the report

    I am trying to show row and column number in the report (not just web preview). I am using Hyperion Reports Version 7.2.5.168

    use a formula column/row. use RANK function in that. (e.g. Rank([A], asc) will sort the rows based on column A values in ascending order)
    you can use this rank in your heading.
    But frankly this is not so easy. You have to do it in a very intelligent way, so that rank gives you column number/row number any how.
    Have a try and let see if you find a appropriate solution.
    Regards,
    Rahul

  • How to create new rows in a JTable dynamically?

    I want to add new rows to a JTable dynamically based on my resultset from the database .
    How to do ?
    Please help me
    Thanks in advance

    Thank u for ur reply .But still i need to clarify something.
    I've used the below code to create a basic table within my frame.
    Object[][] data = {      {"dilipp", "r",      "early", "10","20"}};
    String[] columnNames = {"First Name", "Last Name", "payment", "from", "to"};
    table = new JTable(data, columnNames);
    after this i connect to database and query .The values returned are to be populated in the table created above through say a button "Next" month.
    now my button event goes like this :
    public void actionPerformed(ActionEvent e)
         if (e.getActionCommand().equals("next"))
    here i need to add a new row for the values
    How to add here ?
    please tell me

  • How can i sort the RowSet?

    I have the 2 (master and detail) entity objects, and corresponding 2 (master and detail) view objects.
    Then i've generated the entity object class for the master EO, this class has methods of getting/setting EO attributes, and method for getting a row iterator for the detail object:
    /**Gets the associated entity oracle.jbo.RowIterator */
    public RowIterator getDetailEO() {
    return (RowIterator)getAttributeInternal(DETAILEO);
    Also in that entity object class i've created a method which gets the rows of the detail table, that correspond to the master record, and perform different action on these detail rows:
    RowSet detailRowSet = (RowSet)getDetailEO();
    detailRowSet.executeQuery();
    The question is - How can i sort the rows in that detail RowSet, i.e. order them by their Id? I know that sort operations can be performed on the ViewObjects, but i can't get detail VO from this RowSet.
    Is there a method of sorting/ordering rows in the RowSet?

    You can actually have methods in the VO that access details from the master and vice versa - you define the generation of these methods in you ViewLink properties.
    http://download.oracle.com/docs/html/B25947_01/bcquerying010.htm#sthref327

  • Moving rows in a JTable

    Hello to everybody. I would like to ask you if there is a way to change the order of the rows in a JTable by selecting them and dragging with the mouse just as you can do with columns.
    Best regards.
    Alessandro

    Cheers Richard,
    I'm using TableSorter which is part of the TableSorterDemo in How To Use Tables in the Sun Java tutorial if you want to look - it works fine within the demo. I'm afraid I'm fairly new to java so I'm not sure where to look for the problem. I think I'll try using the default tablemodel, see if that works and then add stuff until it all goes wrong again! Is this sensible? Any more ideas?
    Thomas

  • HOW to emphasize the row selected in a different colour

    Hi all,
    there is any way to set the selected row in a table in a different background-colour?
    i want to emphasize the row selected by user, i try this:
    <af:column headerText="#{res['abogados.nombre']}"
    sortProperty="Nombre" sortable="true"
    binding="#{backing_app_Abogados.column14}"
    id="column14">
    <af:outputText value="#{row.Nombre}"
    binding="#{backing_app_Abogados.outputText14}"
    id="outputText14"
    inlineStyle="background-color:#{bindings.AbogadosView1.currentRow.codigo == row.Codigo ? 'red' : 'transparent'};"/>
    </af:column>
    but this sets the outputText's background to red, i want to set in red all the row..
    any idea?

    Does Rado's following blog entry help: http://adf-rk.blogspot.com/2007/01/adf-oracle-form-like-overflow-in-adf.html

Maybe you are looking for

  • I HAVE PROBLEM WITH UPDATE IN NOKIA N86

    Hello I'm having trouble to update the Nokia N86 At first things are correctly but then fails to update I use the Nokia OVI and error code 12 017 I hope to help me as soon as possible Look at the attachments Attachments: 1.PNG ‏17 KB 3.PNG ‏18 KB 2.P

  • How can I change the language from dutch to english in Photoshop cc 2014 and also the toolbars

    What steps to take for changing the language settings to English so I can follow tutorials?

  • How to prevent update in a tabular form

    Hello, I have a tabular form table based. I need one cannot update rows, but just insert and delete. I'm working on Apex Application Express 4.1.0.00.32. How can i do? Thank you.

  • Reg: measuring point creation and measuring point counter creation

    how to create measuring point and measuring point counter. what is the difference between these two. what is measuring point category, what is measuring point what is measuring point object what is measuring position. can anyone explain me in an easy

  • JSP precompile includes

    I'm trying to precompile my jsp pages and I'm having some difficulties. (WL           5.1 SP9 on Win2k)           It works correctly when I have includes like this:           <%@ include file="common/fwk/framework_start.jsp" %>           but it fails