Multiple column  sorting on JTable data

if any body can please send an example code how multiple column sorting can be done on table data.
condition:- one column should sort in ascending order another column in descending order.
am completly out of ideas it's urgent any help is greatly appritiated
Thank's in advance
sri

I think the crosspost is because the OP was advised to post it in the Swing forum instead (it would've been nice to see the original post closed as well, though). Anyway...
Have you got your table sorting using one column? If so, how have you achieved that (eg, are you using Java 6)?
All you're after is a stable sorting algorithm so that any elements that are the same in the new sorting scheme stay in the same position relative to each other. Then you can just sort by "Column B" then "Column A" to achieve multiple column sorting. I believe that Collections.sort is stable and therefore any sorting approach based on that should be easily modifiable to do what you want.
Hope this helps.

Similar Messages

  • Multiple column sorting in JTable

    There is way to release multiple column sorting in JTable.
    ADF/SWing, Jdev 10.1.3

    I do not know that there is, but it would be really nice!
    regards,
    mario udina

  • Multiple Column sort Pop Up not opening using af:PanelCollection

    Hi guys,
    I have a table in which i want to sort on the basis of Multiple Columns.For that I have used af:PanelCollection but when in menus my advance sort Pop Up is Not opening.I am using jdeveloper 11.1.1.6.
    <af:panelCollection id="pc1" styleClass="AFStretchWidth"
    partialTriggers="t1">
    <f:facet name="menus"/>
    <f:facet name="toolbar"/>
    <f:facet name="statusbar"/>
    <af:table value="#{bindings.xx_sw_vwVO.collectionModel}"
    var="row" rows="#{bindings.xx_sw_vwVO.rangeSize}"
    emptyText="#{bindings.xx_sw_vwVO.viewable ? 'No data to display.' : 'Access Denied.'}"
    fetchSize="#{bindings.xx_sw_vwVO.rangeSize}"
    rowBandingInterval="0"
    width="100%"
    selectionListener="#{bindings.xx_sw_vwVO.collectionModel.makeCurrent}"
    inlineStyle="height:350;"
    rowSelection="single" id="t1"
    partialTriggers="::cb1 ::sor1"
    contentDelivery="immediate" immediate="true"
    autoHeightRows="30" columnSelection="multiple">
    <af:clientListener method="sskuRowSelection" type="click"/>
         <af:serverListener type="sskuRowSelectEvent"
    method="#{DataworkbenchBN.sskurowselect}"/>
    <af:column sortProperty="SskuId" sortable="true"
    headerText="#{bindings.xx_sw_vwVO.hints.SskuId.label}"
    id="c33">
    <af:inputText value="#{row.bindings.SskuId.inputValue}"
    label="#{bindings.xx_sw_vwVO.hints.SskuId.label}"
    required="#{bindings.xx_sw_vwVO.hints.SskuId.mandatory}"
    columns="#{bindings.xx_sw_vwVO.hints.SskuId.displayWidth}"
    maximumLength="#{bindings.xx_sw_vwVO.hints.SskuId.precision}"
    shortDesc="#{bindings.xx_sw_vwVO.hints.SskuId.tooltip}"
    id="it17">
    <f:validator binding="#{row.bindings.SskuId.validator}"/>
    </af:inputText>
    </af:column>

    ADF -- panelCollection multiple column sort
    ~Abhijit

  • Multiple column sorting.

    How does one sort multiple columns( date, String, time etc...). I want to sort by date where two dates can be alike as well. I could use HashMap for that reason.
    Please help.
    Thanks in advance.

    Hi,
    A demo of the comparator class is given below. I've tried to put it into the table class.
    import java.util.*;
    import javax.swing.*;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    class MultipleColumnSortTest
         MultipleColumnSortTest()
              JFrame frame = new JFrame("MultipleColumnSortTest");
              frame.setBounds(10,10,750,550);
              Vector fieldNames = new Vector();
              fieldNames.add("Dates");
              fieldNames.add("Strings");
              Vector dataVector = new Vector();
              for(int i = 0; i < 5; ++ i)
                   Vector row = new Vector();
                   row.add(new Date());
                   row.add("abc" + i%2);
                   dataVector.add(row);
              final SortableDataVector tableModel = new SortableDataVector(dataVector,fieldNames);
              int [] sortIndices = new int[2];
              sortIndices [0] = 0 ;
              sortIndices [1] = 1 ;
              tableModel.setSortPriority(sortIndices);
              JTable table = new JTable(tableModel);
              JScrollPane scrollpane = new JScrollPane(table);
              frame.getContentPane().add(scrollpane);
              JButton button = new JButton("Sort Data");
              frame.getContentPane().add(button,BorderLayout.SOUTH);
              button.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent event)
                        tableModel.setAscendingOrder(!tableModel.isAscendingOrder());
                        tableModel.sort();
              frame.setVisible(true);
         public static void main(String [] args)
              MultipleColumnSortTest appln = new MultipleColumnSortTest();
    class SortableDataVector extends DefaultTableModel implements Comparator
         private int [] indices;
         private boolean isAscendingOrder;
         public SortableDataVector(Vector dataVector, Vector fieldNames)
              super(dataVector,fieldNames);
              setAscendingOrder(true);
         public void setAscendingOrder(boolean b)
              isAscendingOrder = b;
         public boolean isAscendingOrder()
              return isAscendingOrder;
         public void setSortPriority(int [] indices)
              this.indices = indices;
         public int compare(Object o1,Object o2)
              int comparisonResult = compareAscending(o1,o2);
              if(!isAscendingOrder)
                   if(comparisonResult < 0)
                        comparisonResult = 1;
                   else if (comparisonResult > 0)
                        comparisonResult = -1;               
              return comparisonResult;
         private int compareAscending(Object o1, Object o2)
              int comparisonResult = 0;
              if((o1 == null)&&(o2 != null))
                   comparisonResult = -1;
              else if((o1 != null)&&(o2 == null))
                   comparisonResult = 1;
              else if((o1 != null)&&(o2 != null))
                   List firstRow = (List)o1;
                   List secondRow = (List)o2;
                   for(int i = 0; ((i < indices.length)&&(comparisonResult == 0)); ++i)
                        if(indices[i] < firstRow.size())
                             comparisonResult =
                                  DatatypeSensitiveComparator.compare(
                                       firstRow.get(indices),
                                       secondRow.get(indices[i]));
              return comparisonResult;
         public boolean equals(Object obj)
              if(obj == null)
                   return false;
              return this.equals(obj);
         public void sort()
              if((indices != null)&&(indices.length > 0))
                   Collections.sort(dataVector,this);
                   fireTableChanged(new TableModelEvent(this));
    class DatatypeSensitiveComparator
         public static int compare(Object firstValue, Object secondValue)
              int comparisonResult = 0;
              if((firstValue != null)&&(secondValue == null))
                   comparisonResult = 1;
              else if((firstValue == null)&&(secondValue != null))
                   comparisonResult = -1;
              else if((firstValue != null)&&(secondValue != null))
                   Class clazz = firstValue.getClass();
                   if(!clazz.equals(secondValue.getClass()))
                        throw new IllegalArgumentException("Class are not the same ->"
                             + clazz.getName() + ":" +
                             secondValue.getClass().getName());
                   if(clazz.equals(String.class))
                        comparisonResult = ((String)firstValue)
                             .compareTo(((String)secondValue));
                   else if(clazz.equals(Date.class))
                        comparisonResult = ((Date)firstValue)
                             .compareTo(((Date)secondValue));
              return comparisonResult;

  • Multiple Column Sorting in iTunes

    I have seen many conversations around the edges of this, but no answers.  I am curious if it is possible to configure a custom sort in iTunes involving multiple columns. 
    Here is what I would like to end up with - Artist; Sort Show (where I have stored the release date); Album; Disk Number; Track Number.  Seeing my albums in chronological order is the way I always sorted physical albums, I would like to store my virtual ones the same way.  iTunes allows me to use Album by Artist and then sort by Sort Show, but this then displays the tracks in alphabetic order by name! 
    Identifying multiple sort columns (as in Excel) would be ideal.  Thanks for any help you can provide.
    Dave

    It is a database internally, and there are some multivalued sorts, but as users we don't get to specify custom sort orders. Album by Artist is more properly Album by Album Artist and in pseudo-SQL it would go something like this.
    SELECT * FROM Selection ORDER BY SortAlbumArtist, SortAlbum, Disc# , Track#
    Where there is no SortAlbumArtist it is inferred from the first non-empty value of AlbumArtist, SortArtist or Artist.
    Where there is no SortAlbum it is inferred from Album.
    The Disc# & Track# sorts place empties last.
    Presumably the designers think they've included useful options and adding nested sorting features would be too complicated, but you can make suggestions via iTunes Feedback.
    tt2

  • 3.1 Multiple column sorts.

    I have a report which I would like to have multiple columns that default in an ascending sort sequence order.
    Example:
    Column 1 will be sort sequence 2.
    Column 2 will be sort sequence 3.
    Column 3 will be sort sequence 1.
    This was working in 3.0 and now the report only acknowledges the sort sequence of number 1.

    Did you ever get this working again? We'd like to implement something similar - allowing the user to pick a couple of different sort criteria options... How did you implement this in 3.0?
    Thanks,
    Yvette

  • Selecting multiple columns in a jtable

    whats up java programmers,
    i have a problem. i have a jtable with 8 columns. i set a mouse listener to the headers so when i click on one that column underneath the header is highlighted. my problem when i click on one header and then click on another both columns do not stay highlighted. can anyone help please
    matt
    [email protected]

    only way I know is to use
    setColumnSelectionInterval
    and
    addColumnSelectionInterval
    to specifiy which columns.

  • Comparator for multiple column sorting

    Hi,
    Wr have written a below query
    select p.name, o.id, ol.name, pr.name from Person p , Order o , OrderLine ol, Product pr where...
    order by p.key asc, o.key asc, ol.key desc, pr.key desc
    This query is taking lot of time as it seems the ORDER BY is taking more time. Hence we thought of moving sorting in the java side.
    Here whether I need to create 4 comparators
    1) PersonComparator with p.key asc
    2) OrderComparator with o.key asc
    3) OrderLineComparator with ol.key desc
    4) ProductComparator with pr.key desc
    This query returns a list , hence we need to do some thing like this
    Collections.sort(list, new PersonComparator())
    Collections.sort(list, new OrderComparator())
    Collections.sort(list, new OrderLineComparator())
    Collections.sort(list, new ProductComparator())
    Is there any other better way of handling this sorting as 2 fields needs asc and other 2 fields needs desc. Whether we need to create 4 comparators for each object?
    Please clarify. If there is any alternative please specify that as well.
    Thanks.

    >
    This query is taking lot of time as it seems the ORDER BY is taking more time
    >
    Not sure how you drew that conclusion. There is nothing in your post to support it. Oracle is very efficient at sorting.
    More likely the joins and filters (which you didn't show) in your query are either not using existing indexes or the proper indexes don't exist.
    Post the question in the SQL and PL/SQL forum and provide the following information
    1, Read the FAQ at the top of the main forum page for how to post tuning requests - it will include the below info
    2. The 4 digit Oracle version (post results of SELECT * FROM V$VERSION)
    3. The full query
    4. The DDL for the Person, Order and OrderLine tables
    5. The DDL for the existing indexes on the table
    6. The approximate number of records in each table
    7. The expected number of records you expect in the result set
    8. The execution plan for the query
    A. Open a sql*plus session
    B. set serveroutput on
    C. set autotrace traceonly
    D. SELECT P.NAME ... -- that is, execute the query
    E. Copy and Paste the entire output of the result, including the execution plan
    You (or your DBA) need to determine how much work is being done and where the time is being taken before deciding what solutions to consider. The phrase 'taking more time' doesn't mean anything unless you have something to compare it to. Ten seconds to return one record could be slow while ten minutes to return 1 million records could be fast.

  • Sorting multiple columns at a time

    Hi All,
    I have requirement which is web dynpro table loading with the data i need to sort the three columns
    at a time. initially this sorted data is coming from Function module, but now the data is coming from BW to Web dynpro java
    I have one method in sort class which will sort the table on one column at time. i need help in enhancing this method to work for three columns.
      public void sort(String columnId, IWDNode dataSource) {
           IWDTableColumn column =
                (IWDTableColumn) table.getView().getElement(columnId);
           ReversableComparator reversable =
                (ReversableComparator) comparatorForColumn.get(column);
           if (reversable == null)
                return; // not a sortable column
           // remove icon of previously sorted column
           if (currentlySortedColumn != null
                && currentlySortedColumn.getHeader() != null)
                currentlySortedColumn.getHeader().setImageSource(null);
           // bookkeeping
           if (column == currentlySortedColumn) {
                //               reversable.toggleReversed();
           currentlySortedColumn = column;
           // set icon in currently sorted column
           /*if (currentlySortedColumn.getHeader() != null)
                currentlySortedColumn.getHeader().setImageSource(
                     reversable.isReversed()
                          ? "~sapicons/s_b_srtd.GIF"
                          : "~sapicons/s_b_srtu.GIF");
           // sorting
           dataSource.sortElements(reversable);
    Regards,
    Lakshmi Kodavati

    Hi all,
    The solution for EP6.40 Multiple column sorter
    Class file:
    http://wiki.sdn.sap.com/wiki/display/Snippets/Tablesorterbymultiplecolumns%28WebDynproJava%29
    f you does not have WDTableColumnSortDirection try to modify the MultiAttributesNodeComparator and replace WDTableColumnSortDirection with the boolean flag-indicator of the sorting direction. Like this:
    boolean sortAsc = true;  // WDTableColumnSortDirection.UP
    Call this class from web dynpro view
    final MultiAttributesNodeComparator nodeComparator = new MultiAttributesNodeComparator();
                        nodeComparator.sortElements(new String[] {"InvoiceDate","Invoice","Contract"}, true, wdContext.nodeInvoiceListTable());
    Thanks for Siarhei_Pisarenka
    Edited by: narayana on Mar 25, 2010 10:02 AM
    Edited by: narayana on Mar 25, 2010 10:05 AM

  • JTable: Multiple Columns to Single Header

    Hi
    How is it possible to allocate multiple columns in a JTable to the one header.
    I retrieve a resultset from a DB. At present 'firstname' and 'lastname' go into separate columns with separate headers.('firstname' and 'lastname')
    I would like to either combine 'firstname' and 'lastname' then add to the table as one column, or, leave 'firstname' and 'lastname' as is and combine the headers of these columns.
    Not sure how to go about this...
    Any help would be appreciated,
    Thanks
    Gregg

    Look at http://www2.gol.com/users/tame/

  • We used to be able to sort by multiple columns/rows at once by right clicking on the header and choosing show more options-how do we do that in the new Numbers?

    We used to be able to sort by multiple columns/rows at once by right clicking on the header and choosing show more options-how do we do that in the new Numbers?  It doesn't appear anywhere.  Do I now have to sort massive tables by each column one at a time now?  Also there used to be an easier way to merge/unmerge cells without me having to go to the table menu each time.  Am I missing something?

    Multiple column sort is a missing feature in the new version.  Hopefully soon to return. You can do a multicolumn sort by sorting one at a time in reverse order of importance.
    For merging and unmerging cells, I select the cells and right click to bring up the contextual menu. Merge and unmerge are on the menu.  You could also create keyboard shortcuts for Merge Cells and Unmerge Cells in the Table menu.

  • Multiple columns and rows in MessageService

    I am attempting to create a message (via MessageService) which has multiple lines of data, and each line has multiple data columns.
    Background:  My program reads data from a web store, and creates Sales Orders in SBO.  A single run might process multiple orders.  When all orders have been entered, the program should send a (single) message to a list of recipients.  The message will have one line of data for each sales order produced.  Each line will contain two fields: the linked SBO sales order number, and the unlinked web order number.
    When the message is initially created, I'm defining the multiple columns and initializing the data lines:
    pMessageDataColumns = oMessage.MessageDataColumns
    pMessageDataColumn = pMessageDataColumns.Add()
    pMessageDataColumn.ColumnName = "SalesOrder"
    pMessageDataColumn.Link = BoYesNoEnum.tYES
    pMessageDataColumn = pMessageDataColumns.Add()
    pMessageDataColumn.ColumnName = "WebOrder"
    pMessageDataColumn.Link = BoYesNoEnum.tNO
    oLines = pMessageDataColumn.MessageDataLines()
    Later, as each Sales Order is processed, I'm attempting to inject the two data values into the message data:
    oLine = oLines.Add()
    oLine.Value = Str(pOrd.DocNum)
    oLine.Object = 17
    oLine.ObjectKey = Str(pOrd.DocEntry)
    oLine = oLines.Add()
    oLine.Value = pOrd.WebOrder
    The above code would be invoked for each Sales Order processed.  However, it generates an "Internal error (-5002) occurred" when the message is ultimately sent.
    The SDK documentation states:
    The MessageDataLine is a child data structure related to the MessageDataColumn. It contains the value of a specified cell in the Data table, which is defined by its column number (vtIndex of Item of MessageDataColumns) and row number (vtIndex of Item of MessageDataLines).
    I guess I don't understand the relationship between adding a "line" in my data display versus adding data into a "column".  It appears that the "oLines.Add()" is used to bump across the columns of the data.  If so, how do I advance to the next entire row of data in the message?
    Thanks, Dave

        Class Item
            Public ItemCode As String
            Public Dscription As String
        End Class
    Dim ItemCodes as new list( of item)
    Dim one as new item
    one.ItemCode = "ItemCode"
    one. Dscription ="Name of Item"
    itemcodes.add (one)
            Try
                Dim oCmpSvc As SAPbobsCOM.CompanyService = _ocmp.GetCompanyService()
                Dim oMsgSvc As SAPbobsCOM.MessagesService = oCmpSvc.GetBusinessService(ServiceTypes.MessagesService)
                Dim oMsg As SAPbobsCOM.Message = oMsgSvc.GetDataInterface(MessagesServiceDataInterfaces.msdiMessage)
                oMsg.Subject = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                oMsg.Text = Msg
                Dim oMsgDataColumn As SAPbobsCOM.MessageDataColumn
                If ItemCodes.Count > 0 Then
                    oMsgDataColumn = oMsg.MessageDataColumns.Add()
                    oMsgDataColumn.ColumnName = "Product / Item Code"
                    oMsgDataColumn.Link = BoYesNoEnum.tYES
                    For Each oneitem As Item In ItemCodes
                        Dim oMsgDataLine As SAPbobsCOM.MessageDataLine = oMsgDataColumn.MessageDataLines.Add()
                        oMsgDataLine.Object = "4"
                        oMsgDataLine.ObjectKey = oneitem.ItemCode
                        oMsgDataLine.Value = oneitem.Dscription
                    Next
                    oMsgDataColumn = oMsg.MessageDataColumns.Add()
                    oMsgDataColumn.ColumnName = "Description"
                    oMsgDataColumn.Link = BoYesNoEnum.tNO
                    For Each oneitem As Item In ItemCodes
                        Dim oMsgDataLine As SAPbobsCOM.MessageDataLine = oMsgDataColumn.MessageDataLines.Add()
                        oMsgDataLine.Value = oneitem.Dscription
                    Next
                End If
                        Dim oMsgRecipient As SAPbobsCOM.Recipient = oMsg.RecipientCollection.Add()
                        oMsgRecipient.UserCode = "manager"
                        oMsgRecipient.SendInternal = BoYesNoEnum.tYES
                        oMsgRecipient.SendEmail = BoYesNoEnum.tNO
                oMsgSvc.SendMessage(oMsg)
                MsgBox("SAP B1 internal Message sent...")
            Catch ex As Exception
                MsgBox("Unable to send SAP B1 internal message. Error:" + ex.Message)
            End Try
        End Sub

  • How to Sort JTable data using Multiple fields (Date, time and string)

    I have to fill the JTable data with some date, time and string values. for example my table data looks like this:
    "1998/12/14","15:14:38","Unicorn1","row1"
    "1998/12/14","15:14:39","Unicorn2","row2"
    "1998/12/14","15:14:40","Unicorn4","row3"
    "1998/12/17","12:14:12","Unicorn4","row6"
    Now the Sorted Table should be in the following way:
    "1998/12/17","12:14:12","Unicorn4","row6"
    "1998/12/14","15:14:40","Unicorn4","row3"
    "1998/12/14","15:14:39","Unicorn2","row2"
    "1998/12/14","15:14:38","Unicorn1","row1"
    ie First Date field should be sorted, if 2 date fields are same then sort based on time. if date and time fields are same then need to be sorted on String field.
    So if any one worked on this please throw some light on how to proceed. I know how to sort based on single column.
    But now i need to sort on multiple columns.So what is code change in the Comparater class.
    Thanks in advance.. This is urgent....

    I think your Schedule objects should implement Comparable. Then you can sort your linked list using the Collections.sort() method without passing in a Comparator.class Schedule(Date date, String class) implements Comparable
      public void compareTo(Object obj)
        Schedule other = (Schedule)obj;
        return date.getTime() - other.getDate().getTime();
    }

  • Can data be sorted by multiple columns in numbers version 3

    Since upgrading Numbers to version 3 (now 3.0.1) I have been unable to sort data in spreadsheets using multiple columns.  Anyone found a solution?
    Regards
    kurrajong60

    Here's a simple example. Say you want this sorted first by Region then by Name then by Amount.
    So if you set up a sort index column with a simple formula and all you have to do is this (two clicks):
    Giving you this:
    Of course you could do it as I think Hiroto is suggesting and manually sort first by column B, then sort by C, then sort by A.
    But that's a lot of trouble and it's easy to confuse the order so you end up having to start over again.
    SG

  • HT2905 Most all of my 1700 songs have been duplicated in iTunes. I have downloaded the instructions how to delete the duplicates but it says "sort by the date you added" and i have no column that says that. I am running windows xp.

    Most all of my 1700 songs have been duplicated in iTunes. I have downloaded the instructions how to delete the duplicates but it says "sort by the date you added" and i have no column that says that. I am running windows xp.

    Apple's official advice is here... HT2905 - How to find and remove duplicate items in your iTunes library. It is a manual process and the article fails to explain some of the potential pitfalls.
    Use Shift > View > Show Exact Duplicate Items to display duplicates as this is normally a more useful selection. You need to manually select all but one of each group to remove. Sorting the list by Date Added may make it easier to select the appropriate tracks, however this works best when performed immediately after the dupes have been created.  If you have multiple entries in iTunes connected to the same file on the hard drive then don't send to the recycle bin.
    Use my DeDuper script if you're not sure, don't want to do it by hand, or want to preserve ratings, play counts and playlist membership. See this thread for background and please take note of the warning to backup your library before deduping.
    (If you don't see the menu bar press ALT to show it temporarily or CTRL+B to keep it displayed)
    tt2

Maybe you are looking for