简体   繁体   中英

How do I prevent a Java Swing JTable column from being sorted when the user click on the header?

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.

(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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM