3

I am trying to make a clickable column header (so that a method would be called whenever one's clicked).
link to image (since I don't have 10 reputation yet) http://img156.imageshack.us/img156/5764/clickablecolumn.png
The column header is in red rectangle.
What I've done so far is responding whenever any column field (such as the one with James, Benny-G and Rokas) is pressed. The code:

public void mouseClicked(MouseEvent e)
    {
        System.out.println("Mouse clicked");
        TableColumnModel cModel = table.getColumnModel();//cModel - column model
        int selColumn = cModel.getColumnIndexAtX(e.getX());//gets the selected column by clicked x coordinate
    }

1 Answer 1

15

You want to add a mouse listener to the table header, which is represented by JTableHeader:

JFrame frame = new JFrame();
frame.getContentPane().add(new JScrollPane(new JTable(4, 3) {
  {
    getTableHeader().addMouseListener(new MouseAdapter() {
      @Override
      public void mouseClicked(MouseEvent mouseEvent) {
        int index = convertColumnIndexToModel(columnAtPoint(mouseEvent.getPoint()));
        if (index >= 0) {
          System.out.println("Clicked on column " + index);
        }
      };
    });
  }
}));

frame.pack();
frame.setVisible(true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.