JTable可点击列标题

我正在尝试创建一个可单击的列标题(这样只要单击一个方法就会调用一个方法)。
链接到图像(因为我还没有10个声誉) http://img156.imageshack.us/img156/5764/clickablecolumn.png
列标题为红色矩形。
到目前为止,我所做的就是响应任何列字段(例如James,Benny-G和Rokas的字段)。 代码:

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 } 

您想要将鼠标侦听器添加到表头,由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);