Sorting on JTable (JDK 1.6)

Hi,
I currently investigate the new sorting features of JTable in 1.6 (TableRowSorter, etc). By this I came across the following questions:
* Is there a way to access the sorting order of a column? [Background: my comparators are not symmetric: rows which do not contain any value in the given column need to be displayed always at the very end; at the 'beginning' all other rows are sorted accordingly]
* Is there a way to just use the new rendering of the table header, register for sorting events, and do the actual sorting 'manually'? [Background: I already have all the sorting and filtering capabilities in place (in a performance efficient way), but of course want to benefit from the new header rendering]
Any hints are welcome :-)
Thanks in advance,
Hans

Hi,
I currently investigate the new sorting features of JTable in 1.6 (TableRowSorter, etc). By this I came across the following questions:
* Is there a way to access the sorting order of a column? [Background: my comparators are not symmetric: rows which do not contain any value in the given column need to be displayed always at the very end; at the 'beginning' all other rows are sorted accordingly]
* Is there a way to just use the new rendering of the table header, register for sorting events, and do the actual sorting 'manually'? [Background: I already have all the sorting and filtering capabilities in place (in a performance efficient way), but of course want to benefit from the new header rendering]
Any hints are welcome :-)
Thanks in advance,
Hans

Similar Messages

  • Chinese sort in JTable

    Hello
    I used the thread to sort a JTable in Chinese :
    http://forum.java.sun.com/thread.jsp?forum=16&thread=369970
    First, fsato4 (from the thread) says :
    The array java.text.CollationKey[] generated from the method getCollatingKey of the class Collator with the locale java.util.Locale.TRADITIONAL_CHINESE is sorted according to radicals (first level) and strokes(second level) by default.
    I did not find this information on any website (about the Radical sort first and strokes in second). Does anyone know where to get this information ?
    Second :
    I used the code of the thread to sort a JTable (one click on the header) but there is no difference between the "normal" sort (without using Collator) and the use of Collator. Is it normal ?
    Finally is it possible to choose how to sort (strokes first and radicals in second) ?
    Thanks in advance for your help

    First, fsato4 (from the thread) says :
    The array java.text.CollationKey[] generated from the
    method getCollatingKey of the class Collator with the
    locale java.util.Locale.TRADITIONAL_CHINESE is sorted
    according to radicals (first level) and strokes(second
    level) by default.
    I did not find this information on any website (about
    the Radical sort first and strokes in second). Does
    anyone know where to get this information ?
    Actually this is a trivial thing except for a few cases of exceptions like GB2312 (i:pinyin -> ii:radicals) or JIS X 0208 (i:pronunciation -> ii:radicals).
    I refer to 7.1.4 of the book, "Java Internationalization" by Andy Deitsch & David Czarnecki.
    (http://www.oreilly.com/catalog/javaint/)

  • 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

  • Turn off sort in JTable?

    Hi
    How can I turn off auto sort when I click on a column header in JTable obj in JClient/Swing and how to disable edeiting JTable contents.
    Thanks

    Could it be some sort of field issue with the encoding? When viewing on the Mac what screens are you viewing on? Won't they be non interlaced by their nature whilst a tv would be interlaced? Just thinking out loud here as to what might be the cause. We use pre-encoded assets all the time and (unless something has drastically changed in the latest SP- why?) it definitely doesn't re-encode pre-encoded assets.
    I would have thought if it was re-encdoing you would be likely to see blocking than interlacing anyway...
    Try re-encoding a small section - preferably one where you are seeing the interlacing issue worse - with some different settings in Cinemacraft and see if you can trac it down that way perhaps
    Sorry I can't be more help
    Steve Kirkham

  • Focus with JTable - JDK 1.4

    Hi all, I wonder if there's anyone out there know about focus change on jdk1.4, please help me on this if you can:
    with jdk 1.3, when I change focus between components on the same panel, I override this method of JTable to stop focus from being on table's rows only when the table has Focus since it does not move focus to the next component on the panel:
    public boolean isManagingFocus() {
    return false;
    But when I use jdk 1.4 now, this method seems not work as expected anymore. The focus is now switch just between the rows when table has the focus and it does not move the focus to the next components on the panel when I hit TAB key.
    If anyone knows how to fix this, please help me through. Anyhelp will be very appreciated.
    CL

    Sorry it's late but here goes.
    isManagingFocus is deprecated in 1.4 so it's probably best not to use that anyway. It's also called from the constructor of JComponent so if it uses instance variables you might get things like NullPointerException if you're not careful.
    I think the recommended way to approach it is to set the focus traversal keys something like this
    // get your table from somewhere
    JTable table = new JTable();
    // use java.awt.AWTKeyStroke to set up the appropriate focus
    // traversal keys
    AWTKeyStroke tab = AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, 0);
    AWTKeyStroke shiftTab = AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_DOWN_MASK);
    AWTKeyStroke ctrlTab = AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, KeyEvent.CTRL_DOWN_MASK);
    AWTKeyStroke ctrlShiftTab = AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, KeyEvent.CTRL_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK);
    // create a java.util.Set for forwards and backwards focus traversal
    // keys. The actual concrete Set you use probably doesn't matter.
    // I've used a java.util.HashSet
    HashSet forwardKeys = new HashSet();
    HashSet backwardKeys = new HashSet();
    // add the appropriate keys to the appropriate sets
    forwardKeys.add(tab);
    forwardKeys.add(ctrlTab);
    backwardKeys.add(shiftTab);
    backwardKeys.add(ctrlShiftTab);
    // set the focus traversal keys on the table.
    table.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, forwardKeys);
    table.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, backwardKeys);

  • Sorting two Jtables at the same time

    Hello
    I have a problem and I don't know how to solve it.
    I have two Jtables because I need to have some colums fixed and the others can be in a scrollpane. The problem is when I want to sort them. If I sort one the other is not sorted. I use TableSorter from Sun. Let's see a piece of my code:
                TableSorter sorterFixed = new TableSorter(modelFixed);
                fixedTable = new JTable(sorterFixed);           
                sorterFixed.setTableHeader(fixedTable.getTableHeader());
                TableSorter sorter = new TableSorter(model);
                table = new JTable(sorter);
                sorter.setTableHeader(table.getTableHeader());
                jScrollPane = new JScrollPane(table);Anyone knows how can I do it?
    Thanks !!!

    I haven't tested this.. try and let us know
    I guess, TableSorter will fire "fireTableDataChanged()". You can listen for this and update the next table.

  • Category (Group)wise sorting in JTable

    Deadly need your help..I am using jdk1.4 as per the requirement,
    I stuck up where in my JTable i have lot of records..but the first column is having some category..some thing like for category1 have some records and category2 i have some records..when i try to sort on other columns i would like to have them sorted in that first column category wise.Thanks in advance

    Is there any column in subject area for catalog group? if you have you can use directly or else you need to define the group.
    in this case pull category column twice and sales in Criteria
    on 1st category column fx bin tab define the categories, once you done this select sum in results tab
    Hope this helps

  • IP sorting in JTable

    Hi
    How to sort a IP Address column in JTable based on IPAddresses(not String sorting)?
    Thanks

    Are you working on String or InetAddress instances? If the latter, you could use the method "byte[] getAddress()" in a Comparator.

  • Problem with the sorting of  JTable column

    Hi,
    I want to store the positions of the tablecolumns when my program closes and restore them when the program starts again. I store their column-index with their view positions.
    My problem comes when I want to restore them because I cant find a method to move the columns to their new position without compromising the ColumnModel() because then the you edit the model which with you are working with. See my example:
    for (int i = 0;i < getColumnModel().getColumnCount();i++)
    TableColumn tempColumn = getColumnModel().getColumn(i);
    //get it's position
    String position = (String) UserSettingsManager.getInstance().getItemFromMap(positionKey);
    if (position != null)
    getColumnModel().moveColumn(i, Integer.parseInt(position));
    How can I get a list of all the column without using getColumnModel().getColumn() .... or how do I fix this.
    Much thanks,
    Hugo

    See JTable's methods
    public int convertColumnIndexToView(int modelColumnIndex)
    public int convertColumnIndexToModel(int viewColumnIndex)
    for (int i = 0;i < getColumnModel().getColumnCount();i++)
    TableColumn tempColumn = getColumnModel().getColumn(i);
    //get it's position
    String position = (String) UserSettingsManager.getInstance().getItemFromMap(positionKey);
    if (position != null)
    int index=table.convertColumnIndexToView(i);
    getColumnModel().moveColumn(index, Integer.parseInt(position));
    best regards
    Stas

  • Sorting the Model vs sorting the JTable

    So,
    now that I'm starting the rewrite of my program, I wanted to avoid as much dependencies as possible from the table component.
    This, because my table (SwingX JXTable actually) gave me occasional problems and artefacts.
    So, when I want to sort the data in the table, or filter it for example,
    would it be faster to:
    - sort the data model and reset the data in the table
    or
    - don't do anything with the model and let the table do the sorting and filtering?
    Thanks in advance.

    To OP:
    Your question is contradictory.
    First you want to avoid dependencies "from the table component" (I ssume you mean "on JXTable API"). Then you go on asking what would be "faster".
    Other criteria that might be of interest (in addition to "dependencies maintenance" and "speed"), could be:
    - memory usage: if you already know to filter, at the model level, your 1-M customer orders table, into a 10-lines summary for the current customer, then obviously you'll gain memory at the view level.
    - ease of programming: if all order data are in-memory, and you can switch from one customer to the other, filtering at the view level spares one call into the model layer, and probably one DB call as well. A UI developper will be more confortable.
    These are contrived examples, I just want to point out that "it depends" on what are your constraints (interactions, app-specific requirements, staff skill,...).
    AFAIC, I don't remember having problems with sorting and filtering using Swing's native RowSorter API (I did shoot myself in the foot because I sometimes forgot to convert indices, view-to-model and model-to-view, in the event handlers, but once you remember that you're safe).
    Maybe check on a SwingX forum for the (maybe SwingX-specific) artefacts.
    Edited by: jduprez on Jul 13, 2009 7:10 AM

  • Sort a JTable using TableRowSorter

    Hello all,
    I need to sort a table on a column, but the sorting trigger is coded in the program. Currently, I'm using the TableRowSorter.
    All is good, except the sorting is not to be decided by the user, so I don't need the column header click trigger. More over, I also don't need to display on the header anything that might give the user the impression that he can trigger the sort, that is i don't need any sorting arrows.
    Does anyone have an idea how to do this clean? Until now, the only solution I have is to do the sorting myself, but it's somewhat messy.
    Thanks and best regards,
    Domi

    the arrows won't disappear even if there's no comparator / no column is sortableI see, setting a column as non sortable prevents further sorting, but the arrows remain. I don't really think thats a bad thing as it does give the user a visual cue that the table is sorted in that order.
    I agree that it might be a bit confusing in that the user might think they can then resort the table. So maybe the solution is to use a custom renderer. The arrow could be renderer in a "disabled" state to remove the confustion. Or, you could remove the arrow altogether.
    You might be able to start with Darryl's [Default Table Header Cell Renderer|http://www.camick.com/java/blog.html?name=default-table-header-cell-renderer]. I believe the default implementation does paint the arrows, but you should be able to easily customize that behaviour.

  • 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.

  • 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

  • Problem in deleting Rows of JTable after sorting it

    Hi all,
    I'm getting problems in Removing Row(s) after sorting a JTable.
    Please find the code snippets at this URL. Thanks for your time...
    http://forum.java.sun.com/thread.jsp?forum=31&thread=459736&start=15&range=15&hilite=false&q=

    Hi Abhijeet,
    I tried it the way you said using
         wdContext.nodeBirhtday_List().nodeItab().moveFirst();
         //     loop backwards to avoid index troubles
         for (int i = n - 1; i >= 0; --i)
              current_date  = wdContext.nodeBirhtday_List().nodeItab().currentItabElement().getGbdat().getDate();
              current_month = wdContext.nodeBirhtday_List().nodeItab().currentItabElement().getGbdat().getMonth();
              if (( current_date != date_today ) && ( current_month != month_today ))
                   wdContext.nodeBirhtday_List().nodeItab().removeElement(wdContext.nodeBirhtday_List().nodeItab().
                                  getElementAt(i));                
              wdContext.nodeBirhtday_List().nodeItab().moveNext();     
    It adds records...
    According to Valerys Solution, the IPrivate<CustomController> doesnt show me the required nodes. and gives me 'Unable to resolve' error.
    Can you please suggest where I am going wrong
    Regards
    Abdullah

  • How do I do server side sorting in AD with JDK 1.4.2

    In JDK 1.6, I'm able to use SortControl to sort the results from AD on the server side.
    Here is my code that works for JDK 1.6:
    //Set Search Controls          
         SearchControls searchControls = new SearchControls();
         searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
         // Limits the result data for each object
         searchControls.setReturningAttributes(SEARCH_LIST);
            searchControls.setTimeLimit(100000);
         // Setting Sort Controls if sorting was set
         if(sortSearch != null){
             Control[] ctls = new Control[] {new SortControl(new String [] {sortSearch}, Control.CRITICAL)};
             ctx.setRequestControls(ctls);
            //Searching off the base of the tree     
           NamingEnumeration ldapResults = ctx.search("",  filter, searchControls);I want to do the same sorting in JDK 1.4.2
    In that JDK, the SortControl class doesn't exist. Does anyone have a work around for sorting on older JDK versions?
    Thanks

    Thanks adler_steven for the help
    Here is the page where you can download the booster pack jar file
    [http://java.sun.com/products/jndi/downloads/index.html]
    The needed jar file is called ldapbp.jar

Maybe you are looking for