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

Similar Messages

  • Problem with sorting and filtering of table

    Hello,
    using VC 7.1 SP5 I have created [this|http://img232.imageshack.us/img232/2460/screenshotsr0.png] model. The webservice returns a collection of structured elements. The table is meant to display values of top-level attributes. This works as expected.
    However, the table cannot be sorted or filtered. What is the reason for this? How can I fix that?
    I tried to store the result of the web service in a data bridge. That did not succeed.
    Best regards
    Alexander

    Hi Natty,
    How are you trying to sort it?
    I want to be able to sort the table by clicking on the table column headers. Furthermore, I want be able to filter the table by using the built-in table feature. However, table sorting and filtering seem to be disabled for this particular table, whereas other tables in my model provide the desired features.
    Best regards
    Alexander

  • Split Grid, loose sorting and filtering

    Is this the intended behavior? I would rather have my sorting, and filtering retained when using the split knobs.

    While it is not intended, it is a side effect of splitting. When you split the data grid you have 2 full grids which don't know anything of each other. So in the top you can use 1 filter while in the bottom use another and then compare data between the two.
    -kris

  • JTable allows sorting and filtering at same time

    Hi All:
    Any one has experience about having a JTable allows column sorting and row filtering at same time ?
    I've got JTable allows sorting, as well as a JTable allows filtering; but had a hard time to combine these functionality together. It seems I can't use separate TableModel since I need perform these two operations together on on JTable.
    any help is going to be greatly appreciated!

    Have a look at the QuoteTableModel at www.javapractices.com/Topic162.cjp
    (almost at the bottom of the page)

  • Sorting and filtering by select-multi person or group field in the list in SharePoint 2013

    Hi everybody,
    In SharePoint 2013, I have defined a column as "Person or Group" field, which you allow for multiple selections. when I try to sort/filter it by this field in the list. The field doesn't show up in the dropdown. If I changed "Allow multiple
    selections" option to "No" by clicking the column name to edit it in "List Settings", the field can show up sort in the dropdown.
    How about support sorting and filter by select-multiple "Person or Group" field in sharepoint 2013?
    BTW, in SharePoint 2010, it can support this issue no matter what the "Allow multiple selections" option the request is.
    Any help would be great!
    Thanks,
    Jodie

    Hi Jodie,
    Can you please give this as a try.
    To fix the Filter Issue on Assigned To Column. We need to run the following scripts.
    The field which allows more than one values or which allows multiple selections. The multi-valued fileds are non-sortable,
    non-filterable. Multi-valued fields cannot be indexed
    $web=Get-SPWeb
    $list=$web.Lists[] $field=$list.Fields[ColumnName] $strSchema=$field.SchemaXml $str=Schema$strSchema.Replace("Sortable=`"FALSE`"","Sortable=`"true`"")
    $field.SchemaXml = $strSchema
    Krishana Kumar http://www.mosstechnet-kk.com
    Thanks for your reply, I have tried to run the scripts, but it still cannot work. The following is my scripts:
    $web=Get-SPWeb 'http://cst-server-01'
    $list=$.web.Lists["Product Request"]
    $field=$list.Fields["Applicant"]
    $strSchema=$field.SchemaXml
    $str=Schema$strSchema.Replace("Sortable='"FALSE'"", "Sortable='"True'"")
    $field.SchemaXml = $strSchema

  • Question on Sorting and Filtering Viewlet for CR for VS10 Production Rel

    The demo shows great and easy to implement features but near the end when the demonstrator clicks on the Sort for Product Type, the report doesn't sort by this column. Was this because he needed to press "Apply" as he did when he filtered the report by Customer Name fro the change to take effect?

    A promising intro, how did the story unfold?

  • JTable Sorting and Sub Total

    Hi,
    I have written a java applet to display a JTable and also added the Sorting method. My problem is if i try to sort the Total column is also getting sorted. Any help will be much appreciated.
    Thanks
    M.Chockalingam

    Hi,
    I have written a java applet to display a JTable and also added the Sorting method. My problem is if i try to sort the Total column is also getting sorted. Any help will be much appreciated.
    Thanks
    M.Chockalingam

  • List view webpart sorting and filtering requires sign-in.

    I have a list view webpart on a page - both the page and the list are viewable to anonymous users.  The page loads great, but as soon as an anonymous user tries to sort, filter, or use the stock list search box, a login prompt is encountered.  Is
    there a way around this?

    Hi,
    For your issue, I have done a test in SharePoint 2013, and it works fine, I can’t reproduce your issue.
    Navigate to Central Administration ->Application Management->Manage web applications-> Select the web applications and click the “Authentication providers”->Click “Default” link
    “->Check the “Enable anonymous access” option->save
    Navigate to one of the site collections under the configured web application and go to Configure -> Site Settings-> Under the “Users and permissions” section, click the Site 
    permissions->click Anonymous Access in the Ribbon->In this dialog you have three configuration options, I checked Entire Web site.
    Whether the issue occurs in every site collection. Do a test in another site collection, compare the results.
    Whether the issue occurs in every web application. Do a test in another web application, compare the results.
    Here are some useful posts about how to enable anonymous access to a SharePoint 2013 site, you can use as a reference:
    http://blog.cloudshare.com/2012/10/15/how-to-enable-anonymous-access-to-a-sharepoint-2013-site/
    Best regards,
    Lisa Chen

  • POWL ---SORTING AND FILTERING

    Hi,
    Can any one tell me how to  change the column positions and column name .. of a powl table and how to add custom fields into that?

    Try to find the POWL feeder class, this will give you the way for doing that.
    http://wiki.sdn.sap.com/wiki/display/WDABAP/DocumentationInformationabout+POWL
    Best regards,
    Rohit

  • JTable selection and sorting

    hi,
    I have JTable with simple sorting method and i dont use the swing's example.
    I need to add a row in a sorted order and the row selection should remaim intact even after i sort and when i refresh the table the selection should not change.if anybody can help to solve this problem they are most welcome.
    thanks,
    SK

    You are on the right track. First get the rect of the row you want to make visible:Rectangle cellRect = aTable.getCellRect( row, 0, true );Then tell the table to scroll to that rect:aTable.scrollRectToVisible( cellRect );There used to be a bug if you tried to scroll to the last row. I haven't gotten around to seeing if it is fixed 1.4 yet. Here is the full method I use (that works around the bug), enjoy:/**
    * Make sure the passed row is visible in the table (in case it is in a
    * scroll view, and the view is currently viewing elsewhere)
    * @param aTable The table to work with
    * @param row The row number that should be visible
    public static void MakeRowVisible( JTable aTable, int row ) {
        Rectangle cellRect = aTable.getCellRect( row, 0, true );
        if( cellRect != null ) {
            // Have to tweak the height of the table so that if we are
            // scrolling to the bottom, it really shows the bottom (swing bug
            // I guess)
            aTable.setSize( aTable.getWidth(), Integer.MAX_VALUE );
            aTable.scrollRectToVisible( cellRect );

  • JTable woes (JDK 1.5): Sorting and updating data

    So I've been working on this project for a while here that is essentially the front-end to a database system. The data itself is displayed in a JTable derivative. Column 1 is a JComboBox containing a list of companies, Column 2 is a JComboBox containing a list of employees, and the rest of the columns contain information specific to that employee.
    The data for each row is actually contained within a custom TableRowData object, which is used to assign listeners and such:
        private void initComponents() {
            this.organizations.setSelectedEnum(this.data.getOrganizationNumber());
            organizations.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if("comboBoxChanged".equals(e.getActionCommand())) {
                        clearData();
                        try {                 
                            updateEmployees();
                            fireRowDataChanged();
                        } catch (SQLException ex) {
                            Logger.getLogger(VenosTeammateRow.class.getName()).log(Level.SEVERE, null, ex);
            pocs.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {               
                    if("comboBoxChanged".equals(e.getActionCommand())) {
                        try {
                            data = getEmployeeInformation();
                            fireRowDataChanged();
                        } catch (SQLException ex) {
                            Logger.getLogger(VenosTeammateRow.class.getName()).log(Level.SEVERE, null, ex);
        }Ideally, I would like a change in Column 1 to load the employees for the selected company into Column 2. This is working as expected.
    I would also like a change in Column 2 to load the information specific to the selected employee into the rest of the columns. This is also working as expected.
    The problem I am having arises when the data is sorted and THEN a change is made to either column.
    To sort, I am using a custom comparator that keeps track of the sort direction and current sort column.
    In the JTable derivative class, I have a method, sortByColumn(int col):
    public void sortByColumn(int col) {
            this.getColumnModel().getColumn(col).getCellEditor().cancelCellEditing();
            if(this.getSelectedRow() > 0 && this.getSelectedRow() < this.getRowCount())
                this.removeRowSelectionInterval(this.getSelectedRow(), this.getSelectedRow());
            DefaultTableModel mdl = (DefaultTableModel)this.getModel();
            comp.setSortColumn(col);
            Collections.sort(mdl.getDataVector(), comp);
            // Declare and initialize the header
            JTableHeader header = this.getTableHeader();
            // Reset all headers to their identifier values
            for(int i = 0; i < mdl.getColumnCount(); i++) {
                String identifier = header.getColumnModel().getColumn(i).getIdentifier().toString();
                header.getColumnModel().getColumn(i).setHeaderValue(identifier);
            // Find the sort order (for the sorting indicator)
            int sortOrder = comp.getSortOrder(col);
            // Store the identifier text temporarily
            String headerText = header.getColumnModel().getColumn(col).getIdentifier().toString();
            // Declare and initialize the sort indicator based on the sort order
            String sortIndicator;
            switch(sortOrder) {
                case TableRowComparator.ASCENDING:
                    sortIndicator = "  \u2191";
                    break;
                case TableRowComparator.DECENDING:
                    sortIndicator = "  \u2193";
                    break;
                case TableRowComparator.UNSORTED:
                    sortIndicator = "";
                    break;
                default:
                    sortIndicator = "  \u2193";
                    break;
            /* Set the Header to display the text with the indicator. Since
             * this will automatically set the Identifier to the same value,
             * reset it to the value we stored previously.
            header.getColumnModel().getColumn(col).setHeaderValue(headerText+sortIndicator);
            header.getColumnModel().getColumn(col).setIdentifier(headerText);
            // Make sure all the changes are painted
            header.repaint();
            this.repaint();
        }After the sort, the rows are updated and displayed correctly. However, for example with three rows, if by sorting row 1 and row 3 swap, changing the JComboBox in row 3 also updates the data in row 1.
    I'll be converting my code into a short self-contained program momentarily to post on here for a better understanding of what's going on. However, I decided I would post this just in case there were something painfully obvious I missed.
    Thanks.

    Thanks, you've been really helpful :) However, I realized while trying to copy my code to a smaller, self-contained form to illustrate my problems... I never changed the row number in my TableDataRow! So of course the update information, which was relying on the row number stored in the TableDataRow object (and not the actual row number in the model's data vector) updated according to the old row numbers.
    Basically, I coded myself into a corner :P
    Fixed it by making a new comparator to compare TableDataRow objects, and I stored an array of those objects in my custom table model. So the hard work is done on the TableDataRow objects, the data vector is cleared, and then each TableDataRow is added back as a vector.
    Not sure if this is the most elegant solution, but... it works.
    Edited by: GranoblasticMan on Oct 21, 2008 1:11 PM

  • 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();
    }

  • Retrieving sort and filter criteria for interactive report

    I have developed a test management system in APEX. Users log in and see an interactive report with their assignments. Each test they've been assigned occupies one row.
    There is an "Execute" link for each row that takes the user to the test execution page, where they can see the input steps / expected results and report the test passing or failing.
    I've implemented "Next >" and "< Previous" buttons on the execution page, so the user can immediately go forwards or backwards in his assigned tests without having to return to the assignments page and click the Execute link on the next or previous row.
    The test execution page figures out what the next and previous assigned test is using the LAG and LEAD functions, like this:
    lag(assignment_id) over (order by ref_num_full) prev_id,
    lead(assignment_id) over (order by ref_num_full) next_id
    Notice that I've "hardcoded" the over clause to be the reference number of the test.
    The problem here - this solution ignores any custom sorts or filters the user has put in place on the assignments (interactive) report.
    Is there a way I can "grab" the interactive report (1) sort criteria and (2) filter criteria dynamically? I'm thinking I could then use dynamic SQL to build an OVER clause used in the lag/lead calls so that the application now follows whatever sort and/or filter criteria the user has put in place.
    Any help is greatly appreciated...thanks!!

    Thanks WTine!
    I took a look and determined
    - I can get the sort criteria from the APEX_APPLICATION_PAGE_IR_RPT view (SORT_COLUMN_# and SORT_DIRECTION_# columns)
    - I can get the filter criteria from the APEX_APPLICATION_PAGE_IR_COND view
    Regards, Rich

  • 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

Maybe you are looking for

  • Recording from turntables into logic?

    DJs! or anyone else that knows... i want to record a mix onto my laptop from vinyl turntables. ie about 60 mins worth. is logic stable enough to handle recording straight into it for this long? or can anyone recommend a free recording application to

  • How to append records to a field symbols?

    Hi all, is there a way to append records from an internal table fto a field symbol of type table.

  • New xf86-video-mga 14.100 problems

    As I found no way to contact package maintainer, maybe you can post suggestions or comments on this case. Bug report: http://www.freebsd.org/cgi/query-pr.cgi?pr=117726 Patch: http://www.wonkity.com/~wblock/mgapatch/xorg-patch.txt Discussion on this t

  • Best way to handle inversion of custom fields?

    We've added some additional numeric fields, such as quantities, to some of the LO extractors. What is the best way to handle the reversal of these additional fields when reversal records come over on the extractor?  I tried switching on the "inversio

  • The setup has detected that no version of extension builders

    how to solve it?