Add ActionListener to Column Header of JTable

Parag picture Parag · Apr 3, 2012 · Viewed 21.4k times · Source

Is it possible to add an ActionListener to a column header for JTable.

Here is my tableMy table image

Now, I want to add an ActionListener to the column headers (e.g. WQE, SDM) I would like to be able to show the column description in another window.

Answer

Adam picture Adam · Apr 3, 2012

See fully working example below

  • add a MouseListener to the column header
  • use table.columnAtPoint() to find out which column header was clicked

Code:

// example table with 2 cols
JFrame frame = new JFrame();
final JTable table = new JTable(new DefaultTableModel(new String[] {
        "foo", "bar" }, 2));
frame.getContentPane().setLayout(
        new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.getContentPane().add(table.getTableHeader());
frame.getContentPane().add(table);
frame.pack();
frame.setVisible(true);

// listener
table.getTableHeader().addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        int col = table.columnAtPoint(e.getPoint());
        String name = table.getColumnName(col);
        System.out.println("Column index selected " + col + " " + name);
    }
});