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]

Similar Messages

  • How to use AbstractTableModel in JTable

    hi
    i want how to use AbstractTableModel in Jtable
    plz give code

    Multi-post: http://forum.java.sun.com/thread.jspa?threadID=5273661&tstart=0

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

  • Is it better to use AbstractTableModel or DefaultTableModel...?

    Is it better to use AbstractTableModel or DefaultTableModel when subclassing your jtable model? I ask this because while the java tutorial seems to point to the former I've read some people to recommend using the defaulttablemodel. What is the general consensus? Do you have to implement all the methods you need in the defaulttablemodel also? Because right now I think that's the biggest drawback that abstracttablemodel has...

    I ask this because while the java tutorial seems to point to the former (AbstractTableModel)Because they are trying to show an example of how to implement a TableModel. This does not mean you need to create a custom TableModel every time you use a JTable
    I've read some people to recommend using the defaulttablemodel.Because it is fully functional. DefaultTableModel already extends AbstractTableModel to provide this functionality. If it has the functionality that you require then there is no need to create another custom TableModel
    Is it better to use AbstractTableModel or DefaultTableModel...?In general, if the DefaultTableModel does not meet your needs because of the format of your data then you would extend the AbstractTableModel. But if your needs are similiar to the functionality already provided by the DTM then it may be faster/easier to extend it.
    You can't use the AbstractTableModel as is and therefore always need to extend it to implement the functionality that you require. Extending the AbstractTableModel every time doesn't make any sense because you keep doing extra work. So if you do need to extend it you should extend it in a generic way that the classes are reusable.
    Which is why I created the [List Table Model|http://www.camick.com/java/blog.html?name=list-table-model] and [Bean Table Model|http://www.camick.com/java/blog.html?name=bean-table-model]. The idea is to minimize the coding effort involved. They allow you to work with Lists. They can be used as is, or with smaller customization than required if you use the ATM every time.
    Edited by: camickr on May 9, 2009 1:01 AM

  • 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

    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)].

  • The sort field is not used when ordering multiple cds in one alumn folder, how do I correct this?

    It is using the track number and not the sort order field.  The reason I have multiple cds in one alumn is because they are books on cd.

    Sorry for the typo my "b" key was not working correctly.
    The sort field is not used when ordering multiple cds in one albumn folder, how do I correct this?  It is using the track number and not the sort order field.  The reason I have multiple cds in one albumn is because they are books on cd.

  • How do I sort or reorganize while using the new Numbers 3.0

    How do I sort or reorganize while using the new Numbers 3.0; I can't seem to find the sort icon.
    Thanks
    ActiveSolutions

    Yes, I understand the convenience of the old Reorganize panel. I thought it was great. The problem is (I'm guessing) that it is really hard to do something like that in Numbers iOS and Numbers for iCloud. So they gave us features that are more likely to work across all platforms.
    If you need to sort just selected rows you could put the =A&C&B formula (or whatever order you need) in just the rows you need to sort. Leave the other cells in column D blank.
    Or, if you're doing a LOT of partial sorting like that maybe you should have the data in separate tables anyway.
    Not saying it's great... just saying there are workarounds... until (if) something like the Reorganize panel comes back by popular acclaim. 
    SG

  • Need to sort an object array using an element in the object.

    hi all,
    i need to sort an object array using an element in the object.can someone throw some light on this.
    Edited by: rageeth on Jun 14, 2008 2:32 AM

    [http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html]

  • Sort a Grid while using CollapseLevel

    I'm using a Grid with data that I need sorted.  I can use the SQL statement to sort the data how I need it.  But I would also like to use CollapseLevel.  When I do that my data gets scrambled.  Have any of you found a work around for this?

    Hi,
    I´m sorry to tell that there are no good news. The Grid object hasn´t any Ordering functionallity nowadays, and the only way to get that is to execute the SQL statement again. As Grid object needs the format to be designed each time new data is entered, you will have to do it each time the sorting is done.
    Regards,
    Ibai Peñ

  • Deleting a row from a JTable using AbstractTableModel

    Hi,
    Can someone please help me on how should i go about deleting a row in a jtable using the AbstractTableModel. Here i know how to delete it by using vector as one of the elements in the table. But i want to know how to delete it using an Object[][] as the row field.
    Thanks for the help

    Hi,
    I'm in desperate position for this please help

  • Threading design for jTable that uses AbstractTableModel & jProgressBar

    The application consists of a number of jTables that are filled using individual classes that extend AbstactTableModel. I want to use a jProgressBar (setIndeterminate(true)) to show progress is happening when a Search button is pressed. A code snippet is shown below. The method doSearch() calls the classes that populate the jTables. The code works fine but is wrong as components are being updated by a thread other than the EDT. Does this need a complete re-factoring? What design pattern should I be looking to use? Without using this extra thread I cannot get the jProgressBar to show progress.
    if (IbagDatabase.theInstance().isConnected()) {
                  jProgressBarSearch.setVisible(true);
                  jProgressBarSearch.setStringPainted(true); //get space for the string
                  jProgressBarSearch.setIndeterminate(true);
                  jProgressBarSearch.setString("Searching ..."); //display % string             
                  Runnable i = new Runnable()           {
                      public void run() {
                          doSearch();
                          jProgressBarSearch.setIndeterminate(false);
                          jProgressBarSearch.setString("");
                          jProgressBarSearch.setVisible(false);
                  Thread t = new Thread( i );
                  t.start();             
                  //doSearch();
            }

    Using a separate Thread for the long running task is the correct design.
    The only change you need is that when you want to update a GUI component you need to wrap the update code in a SwingUtilities.invokeLater(...). Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html]How to Use Threads for more information.

  • 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

Maybe you are looking for

  • PhotoshopNews: Adobe Photoshop CS3 at a glance!

    http://photoshopnews.com/2006/12/14/adobe-photoshop-cs3-at-a-glance/ Even more content out there now on the home page of PhotoshopNews.com

  • Unable to create connection pooling

    hello everyone, i am trying to implement connection pooling with sybase as the database and tomcat 5 as the container. But this is the exception thats coming : javax.naming.NameNotFoundException: Name jdbc/TestDB2 is not bound in this Context My serv

  • Need help with a basic script to resize image then resize the canvas

    I am new to photoshop scripting, and have come across a need to force an image to be 8"x10" at 300dpi (whether it is vertical or horizontal) I need to maintain the correct orientation in the file, so an Action will not work, I believe I have to imple

  • F-28 - Search Open Items using Multiple Criteria

    Hello, In SAP Transaction F-28, we are trying to select our open items based on the "Invoice Reference" Field.  Our issue is that SAP only allows a maximum of 25 entries, however we have situations where there are 800-1000 entries.  We can cut and pa

  • Macbook Pro Wifi

    whenever i have my macbook on my leg while using it from some reason the wifi stops working and i cannot turn it on one more time im guessing it overheated and i went to apple store beside me and when they run the diagnose they find everything looks