We help IT Professionals succeed at work.

JTable, how to sort when click header

tbboyett
tbboyett asked
on
Medium Priority
470 Views
Last Modified: 2012-06-21
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.
Comment
Watch Question

Sr. Software engineer
CERTIFIED EXPERT
Commented:

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
zzynxSr. Software engineer
CERTIFIED EXPERT

Commented:

Author

Commented:
when I compile it doesn't like the HaderListener, what package does this exist in?
header.addMouseListener(new HeaderListener(header,renderer));

Author

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
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:

Author

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?
zzynxSr. Software engineer
CERTIFIED EXPERT

Commented:
Can you show us more context code of the line

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

?
zzynxSr. Software engineer
CERTIFIED EXPERT

Commented:
Looks like you don't have columns yet, so getColumn(0) leads to that error

Author

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?
zzynxSr. Software engineer
CERTIFIED EXPERT

Commented:
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.

Author

Commented:
please ignore the line
((SortableTableModel)zipsJT.getModel()).setColumnIdentifiers(headerStr);
I was just trying that to see it would help

Author

Commented:
what if i don't get the data till later on?
zzynxSr. Software engineer
CERTIFIED EXPERT

Commented:
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
zzynxSr. Software engineer
CERTIFIED EXPERT

Commented:
>> 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

Author

Commented:
So, can i not set the headers prior to setting the data?
zzynxSr. Software engineer
CERTIFIED EXPERT

Commented:
Try filling the model with one row of null objects
zzynxSr. Software engineer
CERTIFIED EXPERT

Commented:
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]);
        }

 
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

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

unnecesary
zzynxSr. Software engineer
CERTIFIED EXPERT

Commented:
thanx 4 axxepting
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.