JTable Sorting

I have a problem regarding sorting a JTable. Using the autoCreateRowSorter method, the JTable sorts fine visually since the table is only displaying strings, but actually selecting an item in the table causes problems. The Table Model itself stores a Plugin object and on each row displays attributes from a Block object stored in a list. When I double click on a row using the mouse click listener, I want to grab the Block for the row that was clicked. The way I am currently doing this is sending the int for the selected row through the table model to the plugin and then grabbing the block from its list at the index. Of course this doesn't work when the table has been sorted because the order has changed visually but not in the list. Does anyone have any good ideas for fixing it? If there is some way that the Plugin could listen for the table being sorted and know which column was sorted and in which direction, that would work great, otherwise I can not figure out how to attack this problem.

You are looking for [JTable#convertRowIndexToModel(int)|http://java.sun.com/javase/6/docs/api/javax/swing/JTable.html#convertRowIndexToModel(int)].

Similar Messages

  • JTable sorting - problem when adding elements (complete code inside)

    I�m writing this email with reference to a recent posting here but this time with the code example. (I apologize for the duplicated posting � this time it will be with the code)
    Problem: when adding more elements to the JTable (sorted) the exception: ArrayIndexOutOfBoundsException is thrown.
    Example: If the elements in the table are 10 and then the user requests for 8 � the table will produce the correct result. However, if the user will ask for 11 items (>10) the exception will be thrown.
    The program: The program below (compiles and running). A JTable is constructed with 3 items, when you click the button - the return result should be 4 items - this will generate the error, WHY?
    I would highly appreciate your thoughts why this is happening and most importantly � how to fix it.
    Thanks a lot
    3 files:
    (1) TableSorterDemo
    (2) Traveler
    (3)TableSorter
    //TableSorterDemo:
    package sorter;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    * TableSorterDemo is like TableDemo, except that it
    * inserts a custom model -- a sorter -- between the table
    * and its data model.  It also has column tool tips.
    public class TableSorterDemo implements ActionListener
         private JPanel superPanel;
         private JButton clickMe = new JButton("click me to get diff data");
         private boolean DEBUG = false;
         private DefaultListModel defaultListModel;
         private JTable table;
        public TableSorterDemo()
             superPanel = new JPanel(new BorderLayout());
             defaultListModel = new DefaultListModel();
             init1();
            TableSorter sorter = new TableSorter(new MyTableModel(defaultListModel)); //ADDED THIS     
            table = new JTable(sorter);             //NEW
            sorter.setTableHeader(table.getTableHeader()); //ADDED THIS
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            //Set up tool tips for column headers.
            table.getTableHeader().setToolTipText(
                    "Click to specify sorting; Control-Click to specify secondary sorting");
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            superPanel.add("Center", scrollPane);
            superPanel.add("South",clickMe);
            clickMe.addActionListener(this);              
        public JPanel getPanel()
             return superPanel;
        public void init1()
             //in real life this will be done from the db
             Traveler a = new Traveler();
             Traveler b = new Traveler();
             Traveler c = new Traveler();
             a.setFirstName("Elvis");
             a.setLastName("Presley");
             a.setSprot("Ping Pong");
             a.setNumYears(3);
             a.setVegetarian(true);
             b.setFirstName("Elton");
             b.setLastName("John");
             b.setSprot("Soccer");
             b.setNumYears(2);
             b.setVegetarian(true);
             c.setFirstName("shaquille");
             c.setLastName("oneil");
             c.setSprot("Golf");
             c.setNumYears(22);
             c.setVegetarian(true);
             defaultListModel.addElement(a);
             defaultListModel.addElement(b);
             defaultListModel.addElement(c);
        public void init2()
             //in real life this will be done from the db
             Traveler d = new Traveler();
             Traveler e = new Traveler();
             Traveler f = new Traveler();
             Traveler g = new Traveler();
             d.setFirstName("John");
             d.setLastName("Smith");
             d.setSprot("Tennis");
             d.setNumYears(32);
             d.setVegetarian(true);
             e.setFirstName("Ron");
             e.setLastName("Cohen");
             e.setSprot("Baseball");
             e.setNumYears(12);
             e.setVegetarian(true);
             f.setFirstName("Donald");
             f.setLastName("Mac Novice");
             f.setSprot("Vallyball");
             f.setNumYears(1);
             f.setVegetarian(true);
             g.setFirstName("Eithan");
             g.setLastName("Superstar");
             g.setSprot("Vallyball");
             g.setNumYears(21);
             g.setVegetarian(true);
             defaultListModel.addElement(d);
             defaultListModel.addElement(e);
             defaultListModel.addElement(f);
             defaultListModel.addElement(g);            
        class MyTableModel extends AbstractTableModel
             private DefaultListModel myModel;
             public MyTableModel(DefaultListModel m)
                  myModel=m;
            private String[] columnNames = {"First Name",
                                            "Last Name",
                                            "Sport",
                                            "# of Years",
                                            "Vegetarian"};
            public int getColumnCount()
                return columnNames.length;
            public int getRowCount()
                return myModel.size();
            public String getColumnName(int column)
                 return getNames()[column];             
             public String[] getNames()
                  String[] names = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
                  return names;
            public Object getValueAt(int row, int col)
                 return distributeObjectsInTable(row, col, (Traveler) myModel.elementAt(row));
            public Object distributeObjectsInTable(int row, int col, Traveler tr)
               switch(col)
                         case 0:
                              return tr.getFirstName();
                         case 1:
                           return tr.getLastName();
                      case 2:
                           return tr.getSprot();
                      case 3:
                           return new Integer(tr.getNumYears());
                      case 4:
                           return new Boolean (tr.isVegetarian());
                     default:
                         return "Error";
            public Class getColumnClass(int c)
                return getValueAt(0, c).getClass();
        private static void createAndShowGUI()
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("TableSorterDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TableSorterDemo newContentPane = new TableSorterDemo();
            newContentPane.getPanel().setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane.getPanel());
            //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();
         public void actionPerformed(ActionEvent ae)
              if (ae.getSource()==clickMe)
                   defaultListModel.removeAllElements();
                   init2(); //if the size of the model was less than 2 items - the result will be ok.
                              //in other words, if you commens the last 2 rows of this method (addElement(f) & g)
                             // the result will be fine.
                   table.updateUI();          
    }//(2) Traveler
    package sorter;
    public class Traveler
         private String firstName;
         private String lastName;
         private String sprot;
         private int numYears;
         private boolean vegetarian;
         public String getFirstName()
              return firstName;
         public String getLastName()
              return lastName;
         public int getNumYears()
              return numYears;
         public String getSprot()
              return sprot;
         public boolean isVegetarian()
              return vegetarian;
         public void setFirstName(String firstName)
              this.firstName = firstName;
         public void setLastName(String lastName)
              this.lastName = lastName;
         public void setNumYears(int numYears)
              this.numYears = numYears;
         public void setSprot(String sprot)
              this.sprot = sprot;
         public void setVegetarian(boolean vegetarian)
              this.vegetarian = vegetarian;
    }//(3)TableSorter
    package sorter;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.*;
    public class TableSorter extends AbstractTableModel {
        protected TableModel tableModel;
        public static final int DESCENDING = -1;
        public static final int NOT_SORTED = 0;
        public static final int ASCENDING = 1;
        private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
        public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) o1).compareTo(o2);
        public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return o1.toString().compareTo(o2.toString());
        private Row[] viewToModel;
        private int[] modelToView;
        private JTableHeader tableHeader;
        private MouseListener mouseListener;
        private TableModelListener tableModelListener;
        private Map columnComparators = new HashMap();
        private List sortingColumns = new ArrayList();
        public TableSorter() {
            this.mouseListener = new MouseHandler();
            this.tableModelListener = new TableModelHandler();
        public TableSorter(TableModel tableModel) {
            this();
            setTableModel(tableModel);
        public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
            this();
            setTableHeader(tableHeader);
            setTableModel(tableModel);
        private void clearSortingState() {
            viewToModel = null;
            modelToView = null;
        public TableModel getTableModel() {
            return tableModel;
        public void setTableModel(TableModel tableModel) {
            if (this.tableModel != null) {
                this.tableModel.removeTableModelListener(tableModelListener);
            this.tableModel = tableModel;
            if (this.tableModel != null) {
                this.tableModel.addTableModelListener(tableModelListener);
            clearSortingState();
            fireTableStructureChanged();
        public JTableHeader getTableHeader() {
            return tableHeader;
        public void setTableHeader(JTableHeader tableHeader) {
            if (this.tableHeader != null) {
                this.tableHeader.removeMouseListener(mouseListener);
                TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
                if (defaultRenderer instanceof SortableHeaderRenderer) {
                    this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
            this.tableHeader = tableHeader;
            if (this.tableHeader != null) {
                this.tableHeader.addMouseListener(mouseListener);
                this.tableHeader.setDefaultRenderer(
                        new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
        public boolean isSorting() {
            return sortingColumns.size() != 0;
        private Directive getDirective(int column) {
            for (int i = 0; i < sortingColumns.size(); i++) {
                Directive directive = (Directive)sortingColumns.get(i);
                if (directive.column == column) {
                    return directive;
            return EMPTY_DIRECTIVE;
        public int getSortingStatus(int column) {
            return getDirective(column).direction;
        private void sortingStatusChanged() {
            clearSortingState();
            fireTableDataChanged();
            if (tableHeader != null) {
                tableHeader.repaint();
        public void setSortingStatus(int column, int status) {
            Directive directive = getDirective(column);
            if (directive != EMPTY_DIRECTIVE) {
                sortingColumns.remove(directive);
            if (status != NOT_SORTED) {
                sortingColumns.add(new Directive(column, status));
            sortingStatusChanged();
        protected Icon getHeaderRendererIcon(int column, int size) {
            Directive directive = getDirective(column);
            if (directive == EMPTY_DIRECTIVE) {
                return null;
            return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
        private void cancelSorting() {
            sortingColumns.clear();
            sortingStatusChanged();
        public void setColumnComparator(Class type, Comparator comparator) {
            if (comparator == null) {
                columnComparators.remove(type);
            } else {
                columnComparators.put(type, comparator);
        protected Comparator getComparator(int column) {
            Class columnType = tableModel.getColumnClass(column);
            Comparator comparator = (Comparator) columnComparators.get(columnType);
            if (comparator != null) {
                return comparator;
            if (Comparable.class.isAssignableFrom(columnType)) {
                return COMPARABLE_COMAPRATOR;
            return LEXICAL_COMPARATOR;
        private Row[] getViewToModel() {
            if (viewToModel == null) {
                int tableModelRowCount = tableModel.getRowCount();
                viewToModel = new Row[tableModelRowCount];
                for (int row = 0; row < tableModelRowCount; row++) {
                    viewToModel[row] = new Row(row);
                if (isSorting()) {
                    Arrays.sort(viewToModel);
            return viewToModel;
        public int modelIndex(int viewIndex)
            return getViewToModel()[viewIndex].modelIndex;
        private int[] getModelToView()
            if (modelToView == null) {
                int n = getViewToModel().length;
                modelToView = new int[n];
                for (int i = 0; i < n; i++) {
                    modelToView[modelIndex(i)] = i;
            return modelToView;
        // TableModel interface methods
        public int getRowCount() {
            return (tableModel == null) ? 0 : tableModel.getRowCount();
        public int getColumnCount() {
            return (tableModel == null) ? 0 : tableModel.getColumnCount();
        public String getColumnName(int column) {
            return tableModel.getColumnName(column);
        public Class getColumnClass(int column) {
            return tableModel.getColumnClass(column);
        public boolean isCellEditable(int row, int column) {
            return tableModel.isCellEditable(modelIndex(row), column);
        public Object getValueAt(int row, int column) {
            return tableModel.getValueAt(modelIndex(row), column);
        public void setValueAt(Object aValue, int row, int column) {
            tableModel.setValueAt(aValue, modelIndex(row), column);
        // Helper classes
        private class Row implements Comparable {
            private int modelIndex;
            public Row(int index) {
                this.modelIndex = index;
            public int compareTo(Object o) {
                int row1 = modelIndex;
                int row2 = ((Row) o).modelIndex;
                for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
                    Directive directive = (Directive) it.next();
                    int column = directive.column;
                    Object o1 = tableModel.getValueAt(row1, column);
                    Object o2 = tableModel.getValueAt(row2, column);
                    int comparison = 0;
                    // Define null less than everything, except null.
                    if (o1 == null && o2 == null) {
                        comparison = 0;
                    } else if (o1 == null) {
                        comparison = -1;
                    } else if (o2 == null) {
                        comparison = 1;
                    } else {
                        comparison = getComparator(column).compare(o1, o2);
                    if (comparison != 0) {
                        return directive.direction == DESCENDING ? -comparison : comparison;
                return 0;
        private class TableModelHandler implements TableModelListener {
            public void tableChanged(TableModelEvent e) {
                // If we're not sorting by anything, just pass the event along.            
                if (!isSorting()) {
                    clearSortingState();
                    fireTableChanged(e);
                    return;
                // If the table structure has changed, cancel the sorting; the            
                // sorting columns may have been either moved or deleted from            
                // the model.
                if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
                    cancelSorting();
                    fireTableChanged(e);
                    return;
                // We can map a cell event through to the view without widening            
                // when the following conditions apply:
                // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
                // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
                // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
                // d) a reverse lookup will not trigger a sort (modelToView != null)
                // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
                // The last check, for (modelToView != null) is to see if modelToView
                // is already allocated. If we don't do this check; sorting can become
                // a performance bottleneck for applications where cells 
                // change rapidly in different parts of the table. If cells
                // change alternately in the sorting column and then outside of            
                // it this class can end up re-sorting on alternate cell updates -
                // which can be a performance problem for large tables. The last
                // clause avoids this problem.
                int column = e.getColumn();
                if (e.getFirstRow() == e.getLastRow()
                        && column != TableModelEvent.ALL_COLUMNS
                        && getSortingStatus(column) == NOT_SORTED
                        && modelToView != null) {
                    int viewIndex = getModelToView()[e.getFirstRow()];
                    fireTableChanged(new TableModelEvent(TableSorter.this,
                                                         viewIndex, viewIndex,
                                                         column, e.getType()));
                    return;
                // Something has happened to the data that may have invalidated the row order.
                clearSortingState();
                fireTableDataChanged();
                return;
        private class MouseHandler extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                JTableHeader h = (JTableHeader) e.getSource();
                TableColumnModel columnModel = h.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int column = columnModel.getColumn(viewColumn).getModelIndex();
                if (column != -1) {
                    int status = getSortingStatus(column);
                    if (!e.isControlDown()) {
                        cancelSorting();
                    // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
                    // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
                    status = status + (e.isShiftDown() ? -1 : 1);
                    status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
                    setSortingStatus(column, status);
        private static class Arrow implements Icon {
            private boolean descending;
            private int size;
            private int priority;
            public Arrow(boolean descending, int size, int priority) {
                this.descending = descending;
                this.size = size;
                this.priority = priority;
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Color color = c == null ? Color.GRAY : c.getBackground();            
                // In a compound sort, make each succesive triangle 20%
                // smaller than the previous one.
                int dx = (int)(size/2*Math.pow(0.8, priority));
                int dy = descending ? dx : -dx;
                // Align icon (roughly) with font baseline.
                y = y + 5*size/6 + (descending ? -dy : 0);
                int shift = descending ? 1 : -1;
                g.translate(x, y);
                // Right diagonal.
                g.setColor(color.darker());
                g.drawLine(dx / 2, dy, 0, 0);
                g.drawLine(dx / 2, dy + shift, 0, shift);
                // Left diagonal.
                g.setColor(color.brighter());
                g.drawLine(dx / 2, dy, dx, 0);
                g.drawLine(dx / 2, dy + shift, dx, shift);
                // Horizontal line.
                if (descending) {
                    g.setColor(color.darker().darker());
                } else {
                    g.setColor(color.brighter().brighter());
                g.drawLine(dx, 0, 0, 0);
                g.setColor(color);
                g.translate(-x, -y);
            public int getIconWidth() {
                return size;
            public int getIconHeight() {
                return size;
        private class SortableHeaderRenderer implements TableCellRenderer {
            private TableCellRenderer tableCellRenderer;
            public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
                this.tableCellRenderer = tableCellRenderer;
            public Component getTableCellRendererComponent(JTable table,
                                                           Object value,
                                                           boolean isSelected,
                                                           boolean hasFocus,
                                                           int row,
                                                           int column) {
                Component c = tableCellRenderer.getTableCellRendererComponent(table,
                        value, isSelected, hasFocus, row, column);
                if (c instanceof JLabel) {
                    JLabel l = (JLabel) c;
                    l.setHorizontalTextPosition(JLabel.LEFT);
                    int modelColumn = table.convertColumnIndexToModel(column);
                    l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
                return c;
        private static class Directive {
            private int column;
            private int direction;
            public Directive(int column, int direction) {
                this.column = column;
                this.direction = direction;
    }

    The table listens to the TableModel for changes. Changing the table by adding/removing
    rows or columns has no affect on its table model. If you make changes to the table model
    the table will be notified by its TableModelListener and change its view. So tell
    MyTableModel about the change of data:
    public class TableSorterDemo implements ActionListener
        MyTableModel tableModel;
        public TableSorterDemo()
            defaultListModel = new DefaultListModel();
            init1();
            tableModel = new MyTableModel(defaultListModel);
            TableSorter sorter = new TableSorter(tableModel);
        public void actionPerformed(ActionEvent ae)
            if (ae.getSource()==clickMe)
                defaultListModel.removeAllElements();
                init2();
                tableModel.fireTableStructureChanged();
    }

  • JTable sorting and filtering

    I want to sort and Filter JTable.
    Sample code is avialable for this ?.
    Also i would like to know about 3rd party classes.
    Renjith

    Hi,
    There is a such sample on the tutorials for swing/JTable. In this tutorial, u will find 2 files and then make the corresponding classes :
    TableMap and TableSorter
    u can use them like this :
    TableSorter sorter = new TableSorter(myModel);
    //JTable table = new JTable(myModel); //OLD
    JTable table = new JTable(sorter);
    sorter.addMouseListenerToHeaderInTable(table);
    It is very simple, and you can easily modifie these classes to add filters..
    Regards, JFB

  • Problem in JTable Sorting

    I have a table with some entries. The table is a sortable one. I use the standard TableMap.java and TableSorter.java for sorting. The initialisation part consists of the following lines:
    TableSorter sorter = new TableSorter(myTblModel);
    JTable table = new JTable(sorter);
    The problem I have is when I sort the table using the table column header, the rows gets sorted properly. However when I use getValueAt method to retrieve an object at a specified location, it always returns the object that was there before sorting. I dont know where am I going wrong? Can anyone help me please?
    TIA,
    Satish

    Check out the link shown below:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=410651&tstart=0&trange=30
    ;o)
    V.V.
    PS: whatever you did that causes the result to be what you described could be an accidental discovery of a new technique!

  • JTable Sorting... Please Help

    Believe me when I say I have read the forums and the tutorials and the API and still I cannot
    sort my JTable. Just a simple sort on the first column is all I want to do. I am using the default table model and I have the TableSorter and TableMap classes from the tutorial.
    This is my set up:
    tm = new DefaultTableModel(tc,th); //tc is a vector of rows, th is a vector of col headings
    sorter = new TableSorter(tm);
    addrTable = new JTable(sorter);
    I think my biggest problem is how to call the TableSorter method. When I use: TableSorter.sortByColumn(0); I get the error... non-static method cannot be referenced from static context. When I try just sortByColumn(0); of course the compiler cannot resolve symbol.
    What do I do?

    not sure if this will work as i haven't tried it, but i think you'll need to make a call to the sorter.sortByColumn(int, boolean) method. retrive the column index the same way you placed the data in that cell or from a call to :
    TableColumnModel columnModel = tableView.getColumnModel();
    int viewColumn = columnModel.getColumnIndexAtX(e.getX());
    from the point where your cursor is.
    if you do that right after your edit of the cell (where you should be able to get the column index) and also pass in the boolean ascending or descedning value it should sort post-edit.
    again i haven't tried it, and thats just by looking over the code...
    worth a try though... hope it makes sense...
    Takis

  • JTable sorting with frozen columns

    Hi All,
    I have implemented a table with two frozen columns by using two Jtables within a JScrollpane. I've added a TableRowSorter to each table (the fixed and the scrollable one). The first two columns are removed from the main JTable's columnModel and the other columns are removed from the fixed JTable's columnModel. The sorting works fine but currently works on the two tables seperately. They both have the same table model which is one i implemented by extending AbstractTableModel. How can i link up the two tables so that they sort together?
    Thanks

    using the same instance of TableRowSorter with both tables fixed it

  • JTable sorting in 1.5 using AbstractTableModel

    Hi,
    I have a JTable with 7 columns, that uses AbstractTableModel. The Jtable is updated with contents from xml file. I have heard 1.6 provides classes that makes sorting easier, but I need to implement this using 1.5. Could any one provide a sample code for this requirement.
    Regards,
    Arunagiri

    Here is a link to the old 1.5 Swing tutorial. The section on How to Use Tables, includes code for the old way to sort columns in a table.
    [https://www.cs.auckland.ac.nz/references/java/java1.5/tutorial/uiswing/TOC.html]

  • Jtable sorting question - string works, but numbers don't

    Hi,
    I have a Jtable which is populated from an Object two-dimensional array (myData). The object itself already containes string types and int types as appropriate (after a cumbersome type conversion).
    I can sort by the string column, but the number column does not get sorted correctly..i.e it shows 1, 11, 2, 3, 33, 50..etc..
    below is the code I am using:
    JScrollPane jScrollPane1 = new javax.swing.JScrollPane();
    JTable jTable1 = new JTable(myData,columNames);
    jTable1.setAutoCreateRowSorter(true);
    add(new JScrollPane(jTable1));
    jScrollPane1.setViewportView(jTable1);
    Can anyone help?
    thanks

    so, could you show me how to do what he suggests, override the getColumnClass thingy
    I can't figure it out.
    package tableclass;
    import java.awt.BorderLayout;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class EditorTest extends JFrame
        JTable table = new JTable(10, 5);
        public EditorTest()
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane, BorderLayout.SOUTH);
        @Override;
        public class getColumnClass(int columnIndex){
            //idk wtf i'm doing.
        public static void main(String[] args)
            EditorTest frame = new EditorTest();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }

  • Problem on JTable Sorting

    Hi,
    I am using JDK1.6 and I am using the predefined sorter function for sorting the JTable, here I am getting the trouble that My JTable get the Table List from a server, when ever I connect to the server its giving me the list of records, after that if I disconnect the rows are getting removed after that if I am again connected to the server the list is not displaying but its updating. If I remove the sort method its working fine..... Why, its happening like that I am not getting.
    Please, Help to resolve this issue.
    Thank u,
    Sarikakiran

    Hi,
    I resolve the problem
    Regards

  • Need Help regarding JTable Sort?

    Hello friends, i am working on the JTable and want to sort it by clicking on header of the column. I am using jdk1.5 and as my project is based on it so i cant change the jdk. I dont have the rowsorter class in jdk 1.5. So Is there any way through which i can sort the the Jtable by clicking its column header.
    Thanks for any help.

    Here is a link to the 1.5 Swing tutorial:
    https://www.cs.auckland.ac.nz/references/java/java1.5/tutorial/uiswing/TOC.html
    The Table section has a sorting example.

  • JTable: Sort by 1st column

    hi!
    I receive data from a database and create a JTable.
    Now I would like to sort the Data.
    Example:
    Table with ID, Name, Weight, Height
    If I click on the column named "weight" the table should be sorted by the weight...
    Is there a possibility to do that?
    Regards

    Read this section from the Swing tutorial on "How to Use Tables" (actually read all sections). It has sample code for sorting:
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

  • JTable sorting when clicked on header

    In my JTable when clickedon JTable header of a column it doesn't get sorted. how do I make sort when clicked on hearder column?
    Thanks.

    Check out
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#sorting

  • Please help - Jtable sorting columns

    Hi friends...
    I have a JTable whith many different kinds of columns... When I click on a column, it sorts all the table according to the clicked column. How can I make that only the order of THAT column to be reversed (ascending/descending)?Visually, it should only sort the table righthand of the clicked column...
    Any ideas?
    ThanX for your help...

    Hi
    Please find some handy information on JTable and other swing examples.
    http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
    Hope this helps
    Swaraj

  • JTable sorted rows

    How can I sort the rows in a table, but without sorting the actual data in the model.
    This means sorting will have only a visual impact.
    I tried to extend the JTable and keep internally an array of indexes to map the visual rows to the data model rows (I think something similar to how JTable changes the columns visual order without changing the model). This isn't working as I have some problems with the selection. I also want the selection to return the real selected rows (the ones from the model) and not the visual selected ones.
    I think that if the JTable would not use getSelectionModel(), getSelectedRow() and getSelectedRows() internally and only selectionModel protected field this could be done(my code would work). This is because you can return another selection model to the user that will return the real model rows and the JTable can work with the visual rows.
    Thanks,
    Adrian Ber.

    This section from the Swing totorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#sorting]How to Use Table has a sorting class that does what you want.

  • JTable sorter

    Hello,
    to see the wrong sorting, please do the following after launching the programme:
    Click on [Update] to fill the table.
    Click twice in the first column's header - the reverse order looks nice.
    Click [Update] again - and wonder.
    I found a workaround for this malfunctioning in clearing the model line by line,
    before filling it again. So in bUpdate's actionListener comment out the line
    "tblModel.setRowCount(0)" and un-comment "clearModel(tblModel)".
    Then repeat the above steps and see that nothing changes after clicking
    [Update]. The sorting order is obviously remembered; so this is the expected and desired behaviour.
    But now click on [Update 2]. Although the data pairs remain the same, they are
    ordered differently. But the display doesn't change at all. How is that?
    The expected behaviour can be seen, when after program start you alternatively
    click on [Update] and [Update 2]. This works well until a header is clicked
    for sorting. After this, clicking on [Update] and [Update 2] has no effect any
    more.
    Any ideas for that?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class UpdateSortableTable_1 extends JFrame {
      final String HEADER[]= {"No.", "Value"};
      DefaultTableModel tblModel;
      JTable table;
      public UpdateSortableTable_1() {
        super("UpdateSortableTable_1");
        setSize(215, 150);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = getContentPane();
        tblModel = new DefaultTableModel(0, HEADER.length) {
          public Class getColumnClass(int column) {
         Class returnValue;
    /*     The sorter obviously gets fired even if there are no rows. So the
         following line will produce an ArrayIndexOutOfBoundsException:  0 >= 0
         when the model's rowCount is set to 0.
         See bug (6966602) 6967479.
    //     if (column>=0 && column<getColumnCount()) {
         if (getRowCount()>0) { // Use this line as a workaround.
           returnValue= getValueAt(0, column).getClass();
         else {
           returnValue= Object.class;
         return returnValue;
    //     Make read-only
          public boolean isCellEditable(int x, int y) {
         return false;
        tblModel.setColumnIdentifiers(HEADER);
        table = new JTable(tblModel);
        table.setAutoCreateColumnsFromModel(false);
        table.setAutoCreateRowSorter(true);
    //    RowSorter<TableModel> sorter= new TableRowSorter<TableModel>(tblModel);
    //    table.setRowSorter(sorter);
        JScrollPane scrollPane = new JScrollPane (table);
        contentPane.add(scrollPane, BorderLayout.CENTER);
        JPanel buttonPanel= new JPanel();
        JButton bUpdate= new JButton("Update");
        bUpdate.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
         tblModel.setRowCount(0);
    //     clearModel(tblModel);
         tblModel.addRow(new Object[] {1, 1000});
         tblModel.addRow(new Object[] {2, 2000});
         tblModel.addRow(new Object[] {100, 0});
         tblModel.addRow(new Object[] {200, 0});
        buttonPanel.add(bUpdate);
        JButton bUpdate2= new JButton("Update 2");
        bUpdate2.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
         clearModel(tblModel);
         System.out.println("Update 2: "+tblModel.getRowCount());
         tblModel.addRow(new Object[] {100, 0});
         tblModel.addRow(new Object[] {200, 0});
         tblModel.addRow(new Object[] {1, 1000});
         tblModel.addRow(new Object[] {2, 2000});
        buttonPanel.add(bUpdate2);
        contentPane.add(buttonPanel, BorderLayout.SOUTH);
        setVisible(true);
      public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
         new UpdateSortableTable_1();
      public static void clearModel(DefaultTableModel dtm) {
        int j= dtm.getRowCount() -1;
        for (int i=j; i>=0; i--)
          dtm.removeRow(i);
    }

    Jörg wrote:
    The questionable aspect in your model is: is it allowable to return a state-dependent column class?This is only to prevent the ArrayIndexOutOfBoundsException if one wants to use "tblModel.setRowCount(0)".no - that's not what I meant: what I meant with "mutable" (wrong word, most probably) was something like
    DefaultTableModel model = new DefaultTableModel(0, 1);
    Class<?> zeroRowsClass = model.getColumnClass(0);
    model.addRow(new Object[] {1});
    Class<?> nonZeroRowsClass = model.getColumnCalss(0);
    // fails because zero == Object.class, nonZero == Integer.class
    assertEquals(zeroRowsClass, nonZeroRowsClass);
    Deleting the model line by line, one can use the original
         if (column>=0 && column<getColumnCount())
    nitpicking - that's wrong <g> It's client code responsibility to care about pre-conditions: the moment it queries the method with a column outside of the valid range, the error is in the caller. On the other, it's always the model's task to not try access not-existing values. So you always have to guard against zero rows in your model code. The api doc is a bit sparse on the level of the Abstract-/TableModel (stating nothing about pre-conditions). It's only on the level of the default implementation that at least the value accessors state that they are not willing to accept out-of-bounds indices.
         * Returns an attribute value for the cell at <code>row</code>
         * and <code>column</code>.
         * @param   row             the row whose value is to be queried
         * @param   column          the column whose value is to be queried
         * @return                  the value Object at the specified cell
         * @exception  ArrayIndexOutOfBoundsException  if an invalid row or
         *               column was given
        public Object getValueAt(int row, int column) {
            Vector rowVector = (Vector)dataVector.elementAt(row);
            return rowVector.elementAt(column);
        }Strictly speaking, that is very wrong: subclasses/implementors must not tighten super's preconditions, so if super doesn't state anything about validity, implementors have the task to cope with invalid input. Got me started ... back to common sense: in the context of Swing which is very lax on documentation I personally tend to read the default implementation as the "real" design intention. Backtracking from there and widening to the other index taking methods, a getColumnClass doc would read:
         * Returns the most specific superclass for all the cell values
         * in the column. 
         * @param columnIndex  the index of the column
         * @return the common ancestor class of the object values in the model.
         * @throws IllegalArgumentException if columnIndex < 0 or columnIndex >= getColumnCount
        public Class<?> getColumnClass(int columnIndex); what a long long winding road to say:
    // in your code
        public Class<?> getColumnClass(int columnIndex) {
            // this line is duplicating code, in fact grabbing responsibility from the caller which
            // might hide errors in the calling code
            if (columnIndex >= 0 && columnIndex < getColumnCount() {
            // this line is _always_ needed if you access the actual data in this model
            // to deduct the class
            // reason being that the (assumed) precondition of getValueAt is a valid row index
            if (getRowCount() > 0) {
                 // you need to check
                 Object value = getValueAt(0, columnIndex);
                 // a line for robustness (in real code you probably would loop all rows until
                 // finding a not-null value
                 if (value != null) {
                    return value.getClass();
            return Object.class;
        }>
    I hesitate to overwrite the culprit methods, don't know what you mean - there's nothing in DefaultRowSorter you can override. All the (wrong!) comparator caching stuff is private, no way to interfer short of fix in a complete c&p (don't a link but remember that Walter showed something like that in the old sun forum - still didn't add to SwingX, mainly because we needed the old inheritance ... reluctant to do the old trick of subclassing and at the same time c&p everything, like done in BasicXListUI).
    Have a nice week-endThanks, sure enjoy the forum on a dark winter Sunday. You might consider to throw out a helpful or so tag - I don't stand a chance to compete Jerome, as I'm far from his patience with spoon-feeding-accustomed devs <g>
    Cheers
    Jeanette

Maybe you are looking for

  • Adobe Photoshop CS2 Install

    I am attempting to install Adobe Photoshop CS2, I know it is an old version, but I am unable to upgrade at this time.  However, I have the full version of Adobe Photoshop CS2, and when I run the install it states that it is looking for a previous ver

  • How can i show notes in mail like i did in OSX

    How can i show notes in mail like i did in OSX?

  • Iwork 09 (try Iwork)

    Hello, I Have installed Iwork 09 (Family Pack that I JUst purchased, It Is a DVD Version. My question is: After installing it, in the menu location under preferences, it says the word ( Try Iwork . . . ) greyed out of course, works ok. with no proble

  • Is there any way to open an .xlsb file in numbers?

    Our ad department has recently upgraded their windows PCs, and it seems the new default for Excel to save is .xlsb (excel binary workbook). Is there any way to open this in Numbers, or is my only answer to go over to them again and again, to get them

  • Extract of Archived FI Docs

    Hi, I need to extract archived FI docs for a number of GL accounts. Have looked to extract via transaction SARI, however there is no archiving object for FI documents. Please advise on how to proceed Thanks in anticipation. Regards, Abhishek