简体   繁体   English

JTable可点击列标题

[英]JTable clickable column header

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 链接到图像(因为我还没有10个声誉) 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. 到目前为止我所做的就是响应任何列字段(例如James,Benny-G和Rokas的字段)被按下。 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
    }

You want to add a mouse listener to the table header, which is represented by JTableHeader : 您想要将鼠标侦听器添加到表头,由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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM