JTable, how to sort when click header

Hello, I have various information stored data objects and pulled into JTables and I need to find a way so that when a user clicks on a particular header it will sort the data for that column and redisplay the data.  Basically, I can do the sorting, but just need to know how to determine when they click a header and which one they click.  Any suggestions are greatly appreciated.
LVL 5
tbboyettAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
tbboyettAuthor Commented:
when I compile it doesn't like the HaderListener, what package does this exist in?
header.addMouseListener(new HeaderListener(header,renderer));
0
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

tbboyettAuthor Commented:
Sorry about the above question, didn't realize in the example on:
http://www.esus.com/javaindex/j2se/jdk1.2/javaxswing/editableatomiccontrols/jtable/jtablesortrows.html
he had it in the main class
0
objectsCommented:
0
tbboyettAuthor Commented:
Some reason I'm getting:

java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
      at java.util.Vector.elementAt(Vector.java:432)
      at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:280)

at line model.getColumn(i).setHeaderRenderer(renderer);

have you guys ran into that before?
0
zzynxSoftware engineerCommented:
Can you show us more context code of the line

>>        model.getColumn(i).setHeaderRenderer(renderer);

?
0
zzynxSoftware engineerCommented:
Looks like you don't have columns yet, so getColumn(0) leads to that error
0
tbboyettAuthor Commented:
Well I set up the table like this this

zipsJT.setFont(new Font("Arial", 0, 13));
        zipsJT.setBackground(GlobalVarStore.tableBgColor);
        zipsJT.setForeground(GlobalVarStore.tableFontColor);
        zipsJT.setGridColor(GlobalVarStore.tableGridColor);
        zipsJT.setSelectionBackground(GlobalVarStore.tableSelectBgColor);
        zipsJT.setSelectionForeground(GlobalVarStore.tableSelectionFgColor);
        SortableTableModel dm = new SortableTableModel() {
            public Class getColumnClass(int col) {
                switch (col) {
                case 0:
                    return String.class;
                case 1:
                    return Date.class;
                case 2:
                    return Integer.class;
                case 3:
                    return Boolean.class;
                default:
                    return Object.class;
                }
            }

            public boolean isCellEditable(int row, int col) {
                switch (col) {
                case 1:
                    return false;
                default:
                    return true;
                }
            }

            public void setValueAt(Object obj, int row, int col) {
                switch (col) {
                case 2:
                    super.setValueAt(new Integer(obj.toString()), row, col);
                    return;
                default:
                    super.setValueAt(obj, row, col);
                    return;
                }
            }
        };
       
       
        zipsJT.setModel(dm);
        zipsJT.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);


Then I i try to do this:

String[] headerStr = {"Distance","Direction","City","Zip","Count"};
        ((SortableTableModel)zipsJT.getModel()).setColumnIdentifiers(headerStr);
        int[] columnWidth = {60,60,150,60,100};
        SortButtonRenderer renderer = new SortButtonRenderer();
        TableColumnModel model = zipsJT.getColumnModel();
        int n = headerStr.length;
 
        for (int i = 0; i < n; i++) {
        System.out.println("header " + i);
            model.getColumn(i).setHeaderRenderer(renderer);
            model.getColumn(i).setPreferredWidth(columnWidth[i]);
        }

        JTableHeader header = zipsJT.getTableHeader();
        header.addMouseListener(new HeaderListener(header, renderer));

I doesn't make it any further than that, any ideas?
0
zzynxSoftware engineerCommented:
In the file SortableTableExample.java of the example you have first

>> JTable table = new JTable(dm);               // <<< the table is filled here

then

>> TableColumnModel model = table.getColumnModel();         // <<< then you ask the column model
>> int n = headerStr.length;    
>> for (int i=0;i<n;i++) {
>>     model.getColumn(i).setHeaderRenderer(renderer);
>>     model.getColumn(i).setPreferredWidth(columnWidth[i]);    
>> }

When you ask the column model of an empty table it won't contain columns yet.
0
tbboyettAuthor Commented:
please ignore the line
((SortableTableModel)zipsJT.getModel()).setColumnIdentifiers(headerStr);
I was just trying that to see it would help
0
tbboyettAuthor Commented:
what if i don't get the data till later on?
0
zzynxSoftware engineerCommented:
When you call
>> zipsJT.setModel(dm);

dm is still empty.
You have to fill up your data model by calling dm.setDataVector() before doing the rest
0
zzynxSoftware engineerCommented:
>> what if i don't get the data till later on?

delay
>>   model.getColumn(i).setHeaderRenderer(renderer);
>>   model.getColumn(i).setPreferredWidth(columnWidth[i]);
until your model is filled up
0
tbboyettAuthor Commented:
So, can i not set the headers prior to setting the data?
0
zzynxSoftware engineerCommented:
Try filling the model with one row of null objects
0
zzynxSoftware engineerCommented:
String[] headerStr = {"Distance","Direction","City","Zip","Count"};
 dm.setDataVector( new Object[][] {{ null, null, null, null, null }}, headerStr);
 zipsJT.setModel(dm);

followed by

        int[] columnWidth = {60,60,150,60,100};
        SortButtonRenderer renderer = new SortButtonRenderer();
        TableColumnModel model = zipsJT.getColumnModel();
        int n = headerStr.length;
 
        for (int i = 0; i < n; i++) {
        System.out.println("header " + i);
            model.getColumn(i).setHeaderRenderer(renderer);
            model.getColumn(i).setPreferredWidth(columnWidth[i]);
        }

 
0
objectsCommented:
> Try filling the model with one row of null objects

unnecesary
0
zzynxSoftware engineerCommented:
thanx 4 axxepting
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.