Listening for Clicks on a Column Header in a JTable Component

int rows = 10; int cols = 5; JTable table = new JTable(rows, cols); JTableHeader header = table.getTableHeader(); header.addMouseListener(new ColumnHeaderListener()); public class ColumnHeaderListener extends MouseAdapter { public void mouseClicked(MouseEvent evt) { JTable table = ((JTableHeader)evt.getSource()).getTable(); TableColumnModel colModel = table.getColumnModel(); // The index of the column whose header was clicked int vColIndex = colModel.getColumnIndexAtX(evt.getX()); int mColIndex = table.convertColumnIndexToModel(vColIndex); // Return if not clicked on any column header if (vColIndex == -1) { return; } // Determine if mouse was clicked between column heads Rectangle headerRect = table.getTableHeader().getHeaderRect(vColIndex); if (vColIndex == 0) { headerRect.width -= 3; // Hard-coded constant } else { headerRect.grow(-3, 0); // Hard-coded constant } if (!headerRect.contains(evt.getX(), evt.getY())) { // Mouse was clicked between column heads // vColIndex is the column head closest to the click // vLeftColIndex is the column head to the left of the click int vLeftColIndex = vColIndex; if (evt.getX() < headerRect.x) { vLeftColIndex--; } } } }

Comments

10 Mar 2010 - 3:30am by P.S. Lichtenstein - PSL@Lichtenstein.com (not verified)

I find your examples very, very useful.
Is it also possible to post questions ?
(responses will be paid)

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.