1

I have a JTable that has several columns. I wanted to make some of the columns unsortable. How do I do it? I am stuck using Java 1.4 so using TableRowSorter isn't an option since it wasn't introduced until 1.6.

Trippy
  • 131
  • 1
  • 2
  • 7

3 Answers3

5

(for example, only pseudo_code, everything is there hardcoded as example, have to override columns from ColumnModel)

if (column >= 0 && column < getModelWrapper().getColumnCount() 
    && isSortable(column)) {

with

if (column >= 0 && column <=1  /*getModelWrapper().getColumnCount()*/ 
    && isSortable(column)) {

in public void toggleSortOrder(int column) {

then second column isn't sortable

  • if not help you for better help sooner post an SSCCE demonstrated your issue
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
0

Set the rowSorter on the JTable to null. See http://download.java.net/jdk7/archive/b123/docs/api/javax/swing/JTable.html#setRowSorter(javax.swing.RowSorter)

Lee Meador
  • 12,829
  • 2
  • 36
  • 42
0

If you want to sort some and not others, you'll have to implement a listener. I've used something like this:

table.getTableHeader().addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            int col= table.getTableHeader().columnAtPoint(e.getPoint());
            // column number col has been clicked -- sort if necessary,
            // discard the event if sorting is not desired.
            //
        }

    });

Watch out for tables that can drag and drop rows; you can disable this with

table.getTableHeader().setReorderingAllowed(false);
cneller
  • 1,542
  • 1
  • 15
  • 24
  • This does not work, you only add additional logic, but you do not prevent the existing mouselisteners and sorting logic to be applied... Tested like this: table.getTableHeader().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { return; } }); – ruben056 Oct 29 '14 at 12:59
  • True it does not prevent existing listeners from firing. However, if you're using the BasicTableHeaderUI (as I expect most are), you can setReorderingAllowed to false (as indicated) and it will work. – cneller Oct 30 '14 at 14:30