JTable可点击列标题

3
我正在尝试制作一个可点击的列标题(这样每次单击时都会调用一种方法)。
链接到图片(因为我还没有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
    }
1个回答

15

你想要向表头添加鼠标监听器,表头由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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接