Why is my JTable row sort is not working?

Hey all,
I wrote the following code for a JTable and I'm trying to use a table sorter to sort the first column content alphabetically, for now. Later, I'd like to use the third column and sort the table's rows based on ascending dates.
For some reason, my comparator is not being called at all and I'm not sure what I'm doing wrong. I'm using JDK 6, which allows me to use a TableRowSorter. It is the first time I'm using this, so I may not know how to use it correctly. Does anybody have any idea what I'm doing wrong?
Please advice.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Comparator;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
public class MyTable {
     JTable table;
     public MyTable() {
          JFrame frame = new JFrame("My Table");
          JPanel panel = new JPanel(new BorderLayout());
          table = createTable();
          panel.add(table.getTableHeader(), BorderLayout.NORTH);
          panel.add(table);
          frame.getContentPane().add(panel);
          frame.setSize(new Dimension(400,150));
          frame.setVisible(true);
     private JTable createTable()
          Object [][] data = {{"Nazli", "Shahi", "Wed, Mar 31, 1982"},{"Nima", "Sohrabi", "Thu, Jul 15, 1982"},
                                {"Farsheed", "Tari", "Mon, Jun 13, 1967"}, {"Anousheh", "Modaressi", "Tue, Sep 18, 1964"}};
          String [] columnNames = {"First Name","Last Name","DOB"};
          DefaultTableModel model = new DefaultTableModel(data, columnNames);
          table = new JTable(model);
          TableRowSorter sorter = new TableRowSorter(model);
        sorter.setComparator(0, new MyComparator());
         table.setRowSorter(sorter);
          return table;
     private class MyComparator implements Comparator {
          public int compare(Object s1, Object s2) {
               String first = s1.toString();
               String second = s2.toString();               
               System.err.println("returning "+(first.substring(0, 1)).compareTo(second.substring(0, 1)));
               return (first.substring(0, 1)).compareTo(second.substring(0, 1));
     public static void main(String[] args) {
          MyTable test = new MyTable();
}

Alrite, so now I have Date objects in the model instead of String objects. Now, my question is, how can I actually sort the Date column with the latest dates showing on top and earlier dates showing on the bottom?
The table provides a default Comparator to sort dates. You just need to tell the table what type of data is stored in each column. This is done by overriding the getColumnClass() method of JTable or TableModel.
Camickr, you once said that the table provides a default Comparator to sort dates. and I just need to tell the table what type of data is stored in each column. This is done by overriding the getColumnClass() method of JTable or TableModel.
With the current code that I have in getColumnClass I am not able to compare anything yet. Is there anything else I need to do? I'm a bit clueless, so I'd appreciate your help.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class MyTable {
    JTable table;
    DefaultTableModel model;
    public MyTable() {
        JFrame frame = new JFrame("My Table");
        JPanel panel = new JPanel(new BorderLayout());
        table = createTable();
        panel.add(table.getTableHeader(), BorderLayout.NORTH);
        panel.add(table);
        frame.getContentPane().add(panel);
        frame.setSize(new Dimension(400,150));
        frame.setVisible(true);
    private JTable createTable() {
        Object [][] data = {{"Nazli", "Sh", new Date(192837429L)},{"Nima", "So", new Date(1293847L)},
                            {"Farsheed", "T", new Date(9872347892L)}, {"Anousheh", "M", new Date(234321234L)}};
        String [] columnNames = {"First Name","Last Name","DOB"};
        model = new MyTableModel(data, columnNames);
        table = new JTable(model);
        return table;
    public static void main(String[] args) {
        MyTable test = new MyTable();
    private class MyTableModel extends DefaultTableModel {
         public MyTableModel(Object [][] data, String [] columnNames) {
              super(data, columnNames);
         public Class getColumnClass(int column) {
              System.err.println(column);
              if(column==2)
                   return getValueAt(column, 2).getClass();
              else
                   return Object.class;
}

Similar Messages

  • Sorting does not work  with ROW_NUMBER () OVER (ORDER BY

    CREATE OR REPLACE PROCEDURE SP_SALES (
    p_sales_id IN VARCHAR2,
    p_rownnum_from IN NUMBER,
    p_rownnum_to IN NUMBER,
    p_sort_by IN VARCHAR2,
    p_query OUT SYS_REFCURSOR,
    AS
    v_query VARCHAR2 (32000);
    v_sort_list VARCHAR2(32000) ;
    BEGIN
    IF p_spv_sort_by IS NULL THEN
    v_sort_list := 'given_name ASC ' ;
    ELSE
    v_sort_list :=p_spv_sort_by;
    END IF ;
    DBMS_OUTPUT.PUT_LINE ('v_sort_list '||v_sort_list);
    OPEN p_query FOR
    SELECT sales_id,
    item_id,
    order_num,
    employee_name
    ,given_name
    dept_id,
    manager_name,
    ROW_NUM
    FROM
    (SELECT x.*,
    ROW_NUMBER () OVER (ORDER BY v_sort_list ) ROW_NUM
    FROM (sales_id,
    item_id,
    order_num,
    employee_name
    ,given_name
    dept_id,
    manager_name,
    FROM order rvw,
    sales pol,
    emp ca,
    WHERE pol.id = rvw.pr_order_id
    AND ca.empid =pol.employee_id
    AND status = 'SUP') x )
    WHERE ROW_NUM BETWEEN p_rownnum_from AND p_rownnum_to;
    -- ORDER by v_sort_list ;
    DBMS_OUTPUT.PUT_LINE ('v_sort_list '||v_sort_list);
    EXCEPTION
    WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE ('EX ');
    END;
    END;
    SHOW ERRORS
    Sorting does not work. Am I doing something wrong here?
    executing procedure using below
    declare
    x SYS_REFCURSOR;
    y number;
    BEGIN
    SP_SALES('70159_502',1,5, 'GIVEN_NAME'||' ASC' ,:x);
    --dbms_output.put_line (:x);
    END;

    Hello
    Depending on how many different columns you can sort on and the data types of them, it may be feasible for you to include the conditional logic in the existing statement without the need for dynamic sql...
    DTYLER_APP@pssdev2> var p_spv_sort_by varchar2(100)
    DTYLER_APP@pssdev2>
    DTYLER_APP@pssdev2> exec :p_spv_sort_by:='some other column'
    PL/SQL procedure successfully completed.
    P_SPV_SORT_BY
    some other column
    DTYLER_APP@pssdev2>
    DTYLER_APP@pssdev2> WITH source AS
      2  (   SELECT 'a' given_name, 'z' other_column from dual UNION ALL
      3      SELECT 'b' given_name, 'y' other_column from dual UNION ALL
      4      SELECT 'c' given_name, 'x' other_column from dual
      5  )
      6  SELECT
      7      given_name,
      8      other_column,
      9      ROW_NUMBER ()
    10     OVER (
    11        ORDER BY
    12           CASE
    13              WHEN :p_spv_sort_by IS NULL THEN given_name
    14              WHEN :p_spv_sort_by = 'some other column' THEN other_column
    15           END)
    16        ROW_NUM
    17  FROM
    18      source
    19  /
    G O    ROW_NUM
    c x          1
    b y          2
    a z          3
    3 rows selected.
    DTYLER_APP@pssdev2> exec :p_spv_sort_by:=NULL;
    PL/SQL procedure successfully completed.
    P_SPV_SORT_BY
    DTYLER_APP@pssdev2> WITH source AS
      2  (   SELECT 'a' given_name, 'z' other_column from dual UNION ALL
      3      SELECT 'b' given_name, 'y' other_column from dual UNION ALL
      4      SELECT 'c' given_name, 'x' other_column from dual
      5  )
      6  SELECT
      7      given_name,
      8      other_column,
      9      ROW_NUMBER ()
    10     OVER (
    11        ORDER BY
    12           CASE
    13              WHEN :p_spv_sort_by IS NULL THEN given_name
    14              WHEN :p_spv_sort_by = 'some other column' THEN other_column
    15           END)
    16        ROW_NUM
    17  FROM
    18      source
    19  /
    G O    ROW_NUM
    a z          1
    b y          2
    c x          3
    3 rows selected.
    DTYLER_APP@pssdev2>But that would depend on the columns you're sorting on being of the same data type or at least having the ability to convert them to the same data type without loosing the sort order.
    DTYLER_APP@pssdev2> WITH source AS
      2  (   SELECT 'a' given_name, sysdate - 2 other_column from dual UNION ALL
      3      SELECT 'b' given_name, sysdate - 1 other_column from dual UNION ALL
      4      SELECT 'c' given_name, sysdate  other_column from dual
      5  )
      6  SELECT
      7      given_name,
      8      other_column,
      9      ROW_NUMBER ()
    10     OVER (
    11        ORDER BY
    12           CASE
    13              WHEN :p_spv_sort_by IS NULL THEN given_name
    14              WHEN :p_spv_sort_by = 'some other column' THEN other_column
    15           END)
    16        ROW_NUM
    17  FROM
    18      source
    19  /
                WHEN :p_spv_sort_by = 'some other column' THEN other_column
    ERROR at line 14:
    ORA-00932: inconsistent datatypes: expected CHAR got DATE
    DTYLER_APP@pssdev2> WITH source AS
      2  (   SELECT 'a' given_name, sysdate - 2 other_column from dual UNION ALL
      3      SELECT 'b' given_name, sysdate - 1 other_column from dual UNION ALL
      4      SELECT 'c' given_name, sysdate  other_column from dual
      5  )
      6  SELECT
      7      given_name,
      8      other_column,
      9      ROW_NUMBER ()
    10     OVER (
    11        ORDER BY
    12           CASE
    13              WHEN :p_spv_sort_by IS NULL THEN given_name
    14              WHEN :p_spv_sort_by = 'some other column' THEN TO_CHAR(other_column,'YYYYMMDDHH24MISS')
    15           END)
    16        ROW_NUM
    17  FROM
    18      source
    19  /
    G OTHER_COLUMN            ROW_NUM
    a 12-SEP-2011 15:04:19          1
    b 13-SEP-2011 15:04:19          2
    c 14-SEP-2011 15:04:19          3
    3 rows selected.HTH
    David

  • Why is my adobe photoshop elements 12 not working. it says initializing and then it says there is an error and closes itself

    why is my adobe photoshop elements 12 not working. it says initializing then error and shuts itself down.

    Three things you can try:
    1. Clean the superdrive with a proprietory CD/DVD lens cleaner that uses tiny brushes.
    2. Perform an SMC reset:
    Resetting the SMC (System Management Controller) on Intel-based Macs:
    http://support.apple.com/kb/ht3964  and
    http://support.apple.com/kb/HT1237?viewlocale=en_US
    Resetting your Mac's PRAM and NVRAM:
    http://support.apple.com/kb/ht1379
    If you are using a Wireless Keyboard:
    http://support.apple.com/kb/TS3273
    3. Try the free DVD player VLC:
    http://www.videolan.org/vlc/
    which performs better than the built-in DVD Player.

  • Why will the new version of picasa not work on my imac

    Why will my upgraded version of picasa not work on my IMac???HELP
    It will start to load and then error message and cuts off. ( Picasa is photo editing software)

    Picasa is not an Apple product.
    You should ask the developers why they have not updated their application.

  • In SharePoint sorting is not working in the list.

    Sorting is not working when i click on the list column, where the column filed is an people or Group datatype.
    Please help me out in this.
    Ramesh S

    Hi,
    You can refer this post-
    https://social.technet.microsoft.com/Forums/office/en-US/b748bb03-4881-4aa5-9c87-bd4558b9201c/unable-to-sort-task-lists-by-assigned-to-column?forum=sharepointadminprevious
    Thanks,
    Danny
    Please remember to Mark as Answer if it works or vote of it is helpful

  • HT5622 Why is my Apple ID or password not working anymore after I reset my password?

    Why is my Apple ID or password not working anymore after I reset my password?
    It keep asking my password... I have reset it, then, when I enter the new password, it's not accepted...

    Perform a Reset... Try again...
    Reset  ( No Data will be Lost )
    Press and Hold the Sleep/Wake Button and the Home Button at the Same Time...
    Wait for the Apple logo to Appear...
    Usually takes about 15 - 20 Seconds... ( But can take Longer...)
    Release the Buttons...

  • Table sort is not working for columns.

    Hi,
    I am using TableSort.java class. Followed https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sapportals.km.docs/library/user-interface-technology/wd%20java/wdjava%20archive/developing%20with%20tables%20in%20web%20dynpro.pdf
    to create the action and assigned that to onSort event for the table. When I run, I see the ascending-descending icons besides the columns, but nothing happens when I click them. Here is the context.
    Context
    l
    l
    l ---User_Table
             > Email
             > Name
            |
             > Office
    Here Name is a custom string (last name, first name). Also office is a custom string (office1, office2, ...etc).
    Edited by: srinivas M on Feb 8, 2009 6:03 AM
    Edited by: srinivas M on Feb 8, 2009 6:03 AM

    Hi Srinivas,
      If you want to do an initial sort. You have to add the following method to the TableSorter class.
    public void initialSort(String columnId, IWDNode dataSource) {
              // find the things we need
              String direction = WDTableColumnSortDirection.UP;
              IWDTableColumn column = (IWDTableColumn) table.getView().getElement(columnId);
              NodeElementByAttributeComparator elementComparator = (NodeElementByAttributeComparator) comparatorForColumn.get(column);
              if (elementComparator == null){
                   //not a sortable column
                   column.setSortState(WDTableColumnSortDirection.NOT_SORTABLE);
                   return;
              // sorting
              elementComparator.setSortDirection(WDTableColumnSortDirection.valueOf(direction));
              dataSource.sortElements(elementComparator);
    In your wdDoModifyView() after initializing the tablesorter class you have to call the above method.
    if (firstTime) {
                IWDTable table = (IWDTable) view.getElement("Table");
                wdContext.currentContextElement().setTableSorter(
                   new TableSorter(table, wdThis.wdGetSortAction(), null));
                      wdContext.currentContextElement().getTableSorter().initialSort("Your Column ID", wdContext.nodeUser_Search_Results());
    Can you double check in your code if the table is bound to the node "User_Search_Results" and not "User_Table". If the table is bound to the "User_Table" then the sort will not work since in the code you are sorting the node "User_Search_Results".
    If you want to implement sort on only one column you can use the alternate constructor for the TableSorter class.
    TableSorter(IWDTable table, IWDAction sortAction, Map comparators, String[] sortableColumns)
    You have to give a String array of columns that need to be sort enabled.
    Regards,
    Sanyev

  • In formcentral, why does the "proceed to checkout" button not work? on IE I get error " This content cannot be displayed in a frame...

    In formcentral, why does the "proceed to checkout" button not work? on IE I get error " This content cannot be displayed in a frame. To help protect the security of information you enter into this website, the publisher of this content does not allow it to be displayed in a frame ". On Chrome I get nothing but loading.

    Hi,
     This error is generally specific to Internet Explorer and has two possible causes. The most likely explanation is that your browser has unusual browser security settings. I would recommend you try
    resetting your security settings to defaults (varies by version but all essentially the same). You may also have to turn off
    Protected Mode which is enabled by default on some systems. If you’re seeing this error (or a version of it) outside Internet Explorer, you may have a server-level setting that is preventing your content from being framed.
    Reference:https://social.technet.microsoft.com/Forums/exchange/en-US/1460c5a5-6242-4402-9f6b-bc581bf56478/content-cannot-be-displayed-in-a-frame-when-trying-to-add-item?forum=sharepointgeneral
    Thanks,
    Eric
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Eric Tao
    TechNet Community Support

  • Any ideas why my ipod nano 6th gen is not working with Sony SRSGU10IP docking station pls

    any ideas why my ipod nano 6th gen is not working with Sony SRSGU10IP docking station please ? classic working fine, so not the fault of the station itself ? it's been bought as a present for my father & he's confused !

    Check the headphone jack with a flashlight and clean it if necessary. The jack on a new Nano is very tight, be sure you push the headset jack all the way in, the plastic on the headset jack should be flush with the body of the Nano.

  • HT1338 why the map in iphone 5 its not working here United Arab Emirates

    why the map in iphone 5 its not working here United Arab Emirates

    Am having same problem with my iphone 5 ... i can't use facebook and weather app only ... other apps are working perfectly fine ... my phone is on fw 6.0.2 and i think its my firmware problem let me know how did u resolved your's?

  • My mac is running 10.7.2 and wondering why the "find my mac" feature is not working. Instead, it says I need to system upgrade requires.. I believe it's already upgraded together with the 10.7.2

    My mac is running 10.7.2 and wondering why the "find my mac" feature is not working. Instead, it says I need to system upgrade requires.. I believe it's already upgraded together with the 10.7.2

    i get the spinning beach ball in all of my applications
    have a look at this article: Troubleshoot the spinning beach ball

  • Why is the sound on my Envy not working?

    Why is the sound on my Envy not working?  Checked all volume levels, mute, settings etc.

    Hello NellyMac,
    You state you are not getting any sound from your laptop, is that correct? I will be happy to help you.
    Can you please provide the full make and model of the computer you have, If you are unsure where to locate that information have a look at this link for help if needed.
    Please respond back at your earliest convenience.
    Thanks
    Clicking the White Kudos star on the left is a way to say Thanks!
    Clicking the 'Accept as Solution' button is a way to let others know which steps helped solve the problem!

  • Why is the Outlook Favorites sort order not saved?

    I have added the inbox for my main email account as well as inboxes for hotmail and gmail to favorites as well as some folders and search folders. I put the inboxes at the top and exit Outlook. When starting again they are at the bottom instead. Any solution?

    For some reason it works as expected now. Maybe /resetnavpane did the trick anyway even though it at first
    after the reset did not work. Not sure but for now the inboxes shows up at the top as I want to. If this changes again I'll post an update.
    As Deva's said, this is depend on Outlook.xml. If Outlook load the XML failure, we would not receive the correct view. Creating a new Outlook profile would refresh all of files in a new profile, this is a way for troubleshooting and we don't
    need to import all of PSTs.
    Thanks.
    Cheers,
    Tony Chen
    Forum Support
    Come back and mark the replies as answers if they help and unmark them if they provide no help.
    If you have any feedback on our support, please contact
    [email protected]

  • Tabular Form - new row at top not working

    I'm trying to add a new row to the top of a tabular form (not manual) vs the bottom using Denes example - http://apex.oracle.com/pls/otn/f?p=31517:215 but it's not working. I absolutely need the records to sort on the date and time, but when I add a hidden column and sort it in descending order, then sort the date and time both in descending order, it doesn't sort correctly. I tried using the primary key field of the table as the hidden column, sorting nulls first, but the new record opens at the bottom (If I have "sorting nulls first" selected and at the time a new row is added the primary key field is null, why doesn't the new row open at the top?). I added a new field (date field with timestamp) to the query, then deselected "show" in the column attributes...that didn't work. I then selected "show", and changed the tabular form element display as to "Hidden", but then I got an error when I clicked "Add New", and I also added a column to my query via apex_item.hidden but no luck there either. What's the best way to go about this, but still maintain the date and time sort?
    Thank you,
    Tammy

    We did that. It didn't resolve it...
    Also, I compared the images directory from the complete apex 4.1.1. installation and compared it to patch 13331096 (latest 4.1.1 patch). They are identical.
    Any other ideas I can try out?

  • Date Sorting is not working as expected

    Hey,
    I am using Report builder 3.0 to create one daily report where I need daily metrics and I am putting it under columns. I want it in day wise order but somehow it shows data in below format. My dates are in M/D/YYYY format. Notice how 1/10 is displayed
    before 1/2.
    Solutions tried -
    1. I tried Putting Date as first thing in the Sorting section on matrix.
    2. Created Expression in Sort  =Day(Fields!Date.Value)
    3. Created custom code to prepond 0 to day and month so dates becomes in MM/DD/YYYY format but it is not working.
    Query -
     SELECT NON EMPTY { [Measures].[Work Item Count] } ON COLUMNS, NON EMPTY { ([Work Item].[System_State].[System_State].ALLMEMBERS * [Date].[Date].[Date].ALLMEMBERS ) } DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS FROM ( SELECT ( STRTOMEMBER(@FromDateDate,
    CONSTRAINED) : STRTOMEMBER(@ToDateDate, CONSTRAINED) ) ON COLUMNS FROM ( SELECT ( STRTOSET(@WorkItemClaimsSandboxTargetVersion, CONSTRAINED) ) ON COLUMNS FROM ( SELECT ( { [Work Item].[System_WorkItemType].&[Defect] } ) ON COLUMNS FROM ( SELECT ( { [Team
    Project].[Team Project Hierarchy].&[{########-####-####-####-############}] } ) ON COLUMNS FROM [Work Item])))) WHERE ( [Team Project].[Team Project Hierarchy].&[{########-####-####-####-############}], [Work Item].[System_WorkItemType].&[Defect],
    IIF( STRTOSET(@WorkItemClaimsSandboxTargetVersion, CONSTRAINED).Count = 1, STRTOSET(@WorkItemClaimsSandboxTargetVersion, CONSTRAINED), [Work Item].[ClaimsSandbox_TargetVersion].currentmember ) ) CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE,
    FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGS
    Replaced alphanumeric char with #### above.
    Nothing worked. Please help me out here. I am stuck for a month or so. Would appreciate your prompt response.
    Thanks in advance,
    Shrikant

    Hi Shrikant,
    Per my understanding that you have some problem when sorting on the column group on the matrix, which don't work, right?
    I have tested on my local environment and can't produce the issue, you issue can be caused by the wrong method you have used to setting the sorting, you may set the sorting by select the "Tablix Properties", if so, it will not work.
    Please reference to the details information below about how to do the sorting setting:
    Right click the "Column Group" and select the "Group Properties".
    Select the Sorting on the left pane and do the setting like below:
    This setting works fine on my side.
    If you still have any problem, please feel free to ask.
    Regards
    Vicky Liu
    If you have any feedback on our support, please click
    here.
    Vicky Liu
    TechNet Community Support

Maybe you are looking for

  • How to read historical alarms end events from client computer

    How Can I read historical data stored on server computer using Lookout client computer? After installing Lookout client I have not possibility to use NI MAX viewer. What is preferred way for display historical data on client computer? Does client ser

  • Cannot start trial InDesign Server CC Mac

    Following the instructions here: http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/c reativesuite/pdfs/Adobe_Provisioning_Toolkit_Enterprise_Edition_v5.pdf I run the following command: ./adobe_prtk --tool=StartTrial --leid=InDesign

  • Can I "open with" on Catfish gui search results? Yes: see AUR packages

    EDIT March 2, 2014: I have answered my own question below by uploading 4 packages to AUR. Reading through this thread will help to understand what they're for. Here are the 4 packages: https://aur.archlinux.org/packages/gmv/ https://aur.archlinux.org

  • What is the diff bet EKBE anad mseg

    what is the difference between EKBE and MSEG. For what report purpose we can use ekbe. similarly for what report purpose we can use MSEG tables.

  • Bacgflush error: Change REM profile

    Hi Gurus, I have tried to backflush a part number. I get this error: 'Changed REM Profile regarding generation of postprocessing records'. From my knowledge we didn't chnge the REM profile and product cost collecter is also avilable. Please help to r