public void addMouseListenerToHeaderInTable ( JTable table ) { table . setColumnSelectionAllowed ( false ) ; MouseListener mouseListener = new MouseAdapter ( ) { public void mouseClicked ( MouseEvent e ) { if ( e . getSource ( ) instanceof JTableHeader ) { // Always JTableHeader tableHeader = ( JTableHeader ) e . getSource ( ) ; TableColumnModel columnModel = tableHeader . getColumnModel ( ) ; int viewColumn = columnModel . getColumnIndexAtX ( e . getX ( ) ) ; int column = tableHeader . getTable ( ) . convertColumnIndexToModel ( viewColumn ) ; if ( e . getClickCount ( ) == 1 && column != - 1 ) { boolean order = Constants . ASCENDING ; if ( ( e . getModifiers ( ) & InputEvent . SHIFT_MASK ) != 0 ) order = ! order ; if ( ! ( tableHeader . getDefaultRenderer ( ) instanceof SortableHeaderRenderer ) ) tableHeader . setDefaultRenderer ( new SortableHeaderRenderer ( tableHeader . getDefaultRenderer ( ) ) ) ; // Set up header renderer the first time if ( ( ( ( SortableHeaderRenderer ) tableHeader . getDefaultRenderer ( ) ) . getSortedByColumn ( ) == viewColumn ) && ( ( ( SortableHeaderRenderer ) tableHeader . getDefaultRenderer ( ) ) . getSortedOrder ( ) == order ) ) order = ! order ; column = columnToFieldColumn ( column ) ; boolean bSuccess = sortByColumn ( column , order ) ; if ( bSuccess ) setSortedByColumn ( tableHeader , viewColumn , order ) ; } } } } ; table . getTableHeader ( ) . addMouseListener ( mouseListener ) ; }
There is no - where else to put this . Add a mouse listener to the Table to trigger a table sort when a column heading is clicked in the JTable .