将ActionListener添加到JTable的列标题中 [英] Add ActionListener to Column Header of JTable

查看:111
本文介绍了将ActionListener添加到JTable的列标题中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在JTable的列标题中添加ActionListener.

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

这是我的桌子

现在,我想在列标题(例如WQESDM)中添加ActionListener,我希望能够在另一个窗口中显示列说明.

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.

推荐答案

请参见下面的完整示例

  • 将MouseListener添加到列标题中
  • 使用table.columnAtPoint()找出单击了哪个列标题

代码:

// 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);
    }
});

这篇关于将ActionListener添加到JTable的列标题中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆