Jtable sorting column having Jcombobox renderer

Hi
I am trying to sort Jtable column having Jcombobox renderer , please can you give me some idea to do it.
already tried with JDK1.6 table.setAutoCreateRowSorter(true);

To get better help sooner, post a [_SSCCE_|http://mindprod.com/jgloss/sscce.html] that clearly demonstrates your problem.
Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
db

Similar Messages

  • 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 Sorting Columns???

    I have Table with 5 columns and say 3 rows.
    I want to sort the first column.Let us say values in the first column are..CDF, MPC and ABC. so when i click on the column header now the values should be ABC, CDF and MPC..If i click on it again it should sort again reversely..Like MPC, CDF and ABC..We already have example in Java Tutorial TableSorterDemo.java, TableSorter.java..But that sort the column only once.That is it does the sorting and Place ABC, CDF and MPC in order.But when i click on the header again then no sorting takes place where as i want them to show up as MPC,CDF and ABC.Unless u sort the other column and come back to the first column again it doesn't fulfill that requirement.Any help on this is highly appreciated..
    Thanks Much in advance

    Eric,
    Thanks for the reply but iam little confused. Can u
    elaborate and help me more
    Thanks MuchTake a look at TableSorter.java, at the bottom, where it adds a mouse click listener to the header. The applicable line is:
    int shiftPressed = e.getModifiers()&InputEvent.SHIFT_MASK;
    boolean ascending = (shiftPressed == 0); It doesn't reverse sorting. By default, it uses ascending sort. Shift-Click will do descending sort. To do what you want, you should add an accessor method to determine the current value of TableSorter.ascending, then use it to determing the value to use when calling TableSorter.sortByColumn.

  • JTable Selecting Column/Row

    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JTextField;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    public class TableDemo extends JPanel {
        private boolean DEBUG = false;
        public TableDemo() {
             super(new GridLayout(1,0));
             JTable table = new JTable(new MyTableModel());
             table.setPreferredScrollableViewportSize(new Dimension(500, 70));
             JScrollPane scrollPane = new JScrollPane(table); //Set up column sizes.
             initColumnSizes(table); //Fiddle with the Sport column's cell editors/renderers.
             setUpSportColumn(table, table.getColumnModel().getColumn(2)); //Add the scroll pane to this panel.
             add(scrollPane);
        private void initColumnSizes(JTable table) {
             MyTableModel model = (MyTableModel)table.getModel();
             TableColumn column = null;
             Component comp = null;
             int headerWidth = 0;
             int cellWidth = 0;
             Object[] longValues = model.longValues;
             TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
             for (int i = 0; i < 3; i++) {
             column = table.getColumnModel().getColumn(i);
             comp = headerRenderer.getTableCellRendererComponent( null, column.getHeaderValue(), false, false, 0, 0);
             headerWidth = comp.getPreferredSize().width;
             comp = table.getDefaultRenderer(model.getColumnClass(i)). getTableCellRendererComponent( table, longValues, false, false, 0, i);
         cellWidth = comp.getPreferredSize().width;
         if (DEBUG) {
         System.out.println("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth + "; cellWidth = " + cellWidth);
         column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    public void setUpSportColumn(JTable table, TableColumn sportColumn) {
         JComboBox comboBox = new JComboBox();
         comboBox.addItem("SnowBoarding");
         comboBox.addItem("Rowing");
         comboBox.addItem("Knitting");
         comboBox.addItem("Speed reading");
         comboBox.addItem("Pool");
         comboBox.addItem("None of the above");
         sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
         DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
         renderer.setToolTipText("Click for combo box");
         sportColumn.setCellRenderer(renderer);
    class MyTableModel extends AbstractTableModel {
         private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
         private Object[][] data = { {"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)}, {"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)}, {"Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false)}, {"Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true)}, {"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)} };
         public final Object[] longValues = {"Sharon", "Campione", "None of the above", new Integer(20), Boolean.TRUE};
         public int getColumnCount() {
                   return columnNames.length;
    public int getRowCount() {
         return data.length;
    public String getColumnName(int col) {
         return columnNames[col];
    public Object getValueAt(int row, int col) {
         return data[row][col];
    public Class getColumnClass(int c) {
         return getValueAt(0, c).getClass();
    public boolean isCellEditable(int row, int col) {
         if (col < 2) {
         return false;
    else {
    return true;
    public void setValueAt(Object value, int row, int col) {
         if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col + " to " + value + " (an instance of " + value.getClass() + ")");
         data[row][col] = value; fireTableCellUpdated(row, col);
         if (DEBUG) {
         System.out.println("New value of data:");
         printDebugData();
    private void printDebugData() {
         int numRows = getRowCount();
         int numCols = getColumnCount();
         for (int i=0; i < numRows; i++) {
         System.out.print(" row " + i + ":");
         for (int j=0; j < numCols; j++) {
              System.out.print(" " + data[i][j]);
         System.out.println();
         } System.out.println("--------------------------");
    private static void createAndShowGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("TableDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    TableDemo newContentPane = new TableDemo();
    newContentPane.setOpaque(true);
    frame.setContentPane(newContentPane);
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
         public void run() { createAndShowGUI();
    According to this Application the rendering and cell editing is done based on the column. And it displays the same column values for each row.
    I want to use the same application but want to change the[b] set of column values for each row.
    ex:
                    [u] Column values[/u]
    Row 0 =  { Snowboarding ,Rowing, Knitting.......}
    Row 2 = {  A,B,C,..........}
    Row 3 = {1,2,3}
    Help PLEASE!!!!
    thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    This posting shows one way:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=446022

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

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

  • Sort columns in matrix report

    Hi all
    I create matrix report( in version 9i)
    I want sort columns of report
    when i use order by it sort rows but i want sort columns
    my query is like this:
    SELECT
    Code,
    name,
    DECODE(cons_code, '1', 'A',
    '2', 'B',
    '3','C',
    '4', 'D',
    '5', 'E') Activity,
    SUM(amnt) amount
    From Mytable
    Where ....
    group by
    Code,
    DECODE(cons_code, '1', 'A',
    '2', 'B',
    '3','C',
    '4', 'D',
    '5', 'E')
    my group base on code
    my columns base on Activity
    and cells are Amount
    my report result is:
    ........ B E D A C
    name1 1 1 1 1 2
    name2 3 4 8 6 1
    I want this :
    ........ A B C D E
    name1 1 1 1 1 2
    name2 3 4 8 6 1
    ....

    Hello,
    How about this?
    SELECT Code, name,
    DECODE(cons_code, '1', 'A', '2', 'B', '3','C', '4', 'D','5', 'E') Activity, SUM(amnt) amount
    From Mytable
    WHERE ....
    GROUP BY Code, name, DECODE(cons_code, '1', 'A', '2', 'B', '3','C', '4', 'D', '5', 'E')
    ORDER BY code, DECODE(cons_code, '1', 'A', '2', 'B', '3','C', '4', 'D', '5', 'E')

  • How do i change the color of a JTable's column names

    hai,
    i'm very new to java and trying to customize the look of a JTable.
    how do i change the color of a JTable's Column names. i know its very simple, i just couldn't figure out how to do it!!
    thanx in advance

    table.getTableHeader().setForeground(Color.RED);

  • 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

  • A simple question about wrong sorting with multiple sort columns in Excel 2010

    Hi, everyone! I have encountered a problem that I don't know how to explain.
    So I post it here because I don't know if there is another more relevant forum...
    I have a data sheet with the students' scores for the course. 
    All the data were generated with the randbetween function,
    and pasted with the values.
    To rank the students by their performance,
    I did the sort with the column "total score" as the first sort-column
    and "final term" as the second.
    The weird thing to me is that the order of the data seems problematic.
    That is, all the rows are sorted correctly with the first sort-column.
    But for the rows with the same values of the first sort-column,
    there are some rows whose values of the second sort-column are out of order.
    (please look at the data file at
    www_dot_kuaipan_dot_cn/file/id_67204268108546068_dot_htm
    Please change the "_dot_" to the real literal dot.
    Especially the rows with 56.7 as the first sort-column value
    and some other values near the tail of the list.)
    I tried to manually input and sort the same values of both columns
    in a near-by region. The result was correct.
    When some friend copied all the data to paste in Notepad,
    and reload them in excel. The problem disappears.
    Some friend also tried to wrap a round function at the values of the 1st sort-column,
    the sorting order became correct!
    But they could not explain why either.
    How confusing! I even tried to swap the first and secod sort-column;
    the output was right.
    All the data were generated by randbetween function and pasted with values.
    Where could all the special characters, if any, come?
    Can anyone give me an explanation? I would be very grateful.
    Thanks in advance!

    Re:  Sort is not in proper order
    Sounds as if the data includes spaces or hidden characters that are affecting the sort.
    That is indicated by the fact that manually entering the data resolves the problem.
    Note:  You can use a public file storage website to hold your file and add the link to it in your post.
    Jim Cone
    Portland, Oregon USA
    Special Sort excel add-in (30+ ways to sort) - 3 week no obligation trial
    https://jumpshare.com/b/O5FC6LaBQ6U3UPXjOmX2

  • How to create Tree format in Table Rn in one Column having data?

    Hi Gurus,
    i got the new requirement it's very interesting pl z help me...
    My Requirement is i have one Table Rn in Table Rn having 5 columns There here one column name is 'Competencies ' That Competencies column having the more rows liki
    FUNC.ADMIN.Achievement Orientation
    FUNC.ADMIN.Administrative Assistance and Support
    FUNC.ADMIN.Administrative(ADMIN)
    This is one column data my Requirement is now
    FUNC
    +ADMIN
    +Achievement Orientation
    like clients are expecting pl z tell me how to approach in this requirement and what are prerequisites are needed ...plz help me it's urgent requirement.
    Regards,
    Srini

    Hi Gyan,
    Thank's for valuable suggestions
    My Requirement is This ...
    "Competencies" Table Layout: (InstTableLayout)
    COMPETENCIES (COLUMN NAME)
    BEHV.Generic.Communication(BEHV)
    BEHV.Generic.Planning, Organizing & Time Management
    BEHV.Generic.Problem Solving Ability
    BEHV.Generic.Productivity
    BEHV.Generic.Punctuality
    like number of rows are there now Tree format is row data
    like each column divided each one
    ex:
    + BEHV
    *|*
    +Generic
    *|*
    +Communication(BEHV)
    like he expected client in tree format pl z tell me how to approach in this requirement and what are the prerequisites are required .....
    Regards,
    Srini
    Edited by: 876628 on Dec 1, 2011 8:37 PM
    Edited by: 876628 on Dec 1, 2011 8:37 PM

  • How can I get (using API) the current sort column for some report

    hello,
    How can I get (using API) the current sort column for some report ? For example something like "fsp_sort_1_desc" - if the user sorts by the first column ?
    I cannot use the :REQUEST for this, sometimes the current sort column is not in the :REQUEST, but it is still active.
    I thought it was posssible by using
    APEX_UTIL.GET_PREFERENCE (
    p_preference IN VARCHAR2 DEFAULT NULL,
    p_user IN VARCHAR2 DEFAULT V('USER'))
    RETURN VARCHAR2;
    function, but I don't really know which preference should I pass as parameter.
    looking in WWV_FLOW_PREFERENCES$, i saw preferences_names like FSP4000_P527_R6281510839654570_SORT , I'm not sure how this name is formed.
    I'm using generic columns for that complex report (which has a flexible number of columns shown), and the idea is that sometimes I have to overwrite that sort column, in case the user chose the version of the report with fewer columns than the previous one.
    Can I get (using API) a list of all preferences set for some user ?
    Thank you,

    seems that it is FSP<app_number>P<pagenumber>R<regionnumber>_SORT.
    is there anyplace where I can get these kind of things documented ?
    Thank you.

Maybe you are looking for

  • How do you change the language hyphenation engine in Photoshop without changing the User Interface (UI)?

    I'm working on some documents in Spanish. I'm having issues because the hyphenation function is in English. I want the program to follow the proper Spanish hyphenation rules without changing my English UI.

  • Can somebody explain what is LUW ?

    Hi Gurus, can somebosy explain me what is LUW(Logical unit of work). I went through some book, but i am not able to get the concept. can somebody help me out inthis Thanks & regards Rajesh Meda

  • CONVERSION TYPE

    Hi All Could you help me with conversion type. I have 2 IO IO_PRC (price ) and IO_QUANT( Quantity). I have selected fixed currency and unit in the IO definataion. When I creating transformation i get the message conversion type missing. why is this.

  • Want the remove IPTC fields by export

    I have a lot of pictures that i will export with a preset. Because of privacy matters i must remove the IPTC-fields such as sublocation, city, state / province. Can get that done. To much pictures to remove these fields in Photoshop after the export

  • # at the end of file

    I'm uploading the .txt file in application server using function module ARCHIVFILE_CLIENT_TO_SERVER. When file is uploaded successfully on application server, character # is getting updated at the end of each line. Is anyone aware of the reason for t