Java 将ActionListener添加到JTable的列标题

Java 将ActionListener添加到JTable的列标题,java,swing,jtable,actionlistener,jtableheader,Java,Swing,Jtable,Actionlistener,Jtableheader,是否可以将ActionListener添加到JTable的列标题中 这是我的桌子 现在,我想在列标题中添加一个ActionListener(例如WQE,SDM),我希望能够在另一个窗口中显示列描述。请参阅下面的完整工作示例 向列标题添加鼠标侦听器 使用table.columnAtPoint()查找单击的列标题 代码: 是的,这是可能的。可以在列标题和单元格上添加鼠标事件,如下所示: private class MyMouseAdapter extends MouseAdapter {

是否可以将
ActionListener
添加到
JTable
的列标题中

这是我的桌子


现在,我想在列标题中添加一个
ActionListener
(例如
WQE
SDM
),我希望能够在另一个窗口中显示列描述。

请参阅下面的完整工作示例

  • 向列标题添加鼠标侦听器
  • 使用table.columnAtPoint()查找单击的列标题
代码:


是的,这是可能的。可以在列标题和单元格上添加鼠标事件,如下所示:

private class MyMouseAdapter extends MouseAdapter {

    public void mousePressed(MouseEvent e) {

        if (table.equals(e.getSource())) {

            int colIdx = table.columnAtPoint(e.getPoint());
            int rowIdx = table.rowAtPoint(e.getPoint());
Object obj = table.getModel().getValueAt(rowIdx, colIdx) ;//This gets the value in the cells
           String str = obj.toString();//This converts that Value to String
           JTextField somefield = new JTextField();//Choose a JTextField
           somefield.setText(str);//Populates the Clicked value to the JTextField

            System.out.println("Row: " + rowIdx + " " + "Colulmn: " + colIdx);
        }
        else if (header.equals(e.getSource())) {

            int selectedColumnIdx = header.columnAtPoint(e.getPoint());
            String colName = table.getColumnName(header.columnAtPoint(e.getPoint()));

            System.out.println("Column Name: " + colName);
            System.out.println("Selected Column: " + selectedColumnIdx);
        }
    }
}

修改示例代码以适合您的口味和偏好

另请参见此。最好在桌子上使用a。页眉侦听器会重复@Adam的更早版本。+1这是教程中建议的方法,并附有插图。太棒了!我从未意识到头上的mouseclick事件比表上的事件要好。:D
private class MyMouseAdapter extends MouseAdapter {

    public void mousePressed(MouseEvent e) {

        if (table.equals(e.getSource())) {

            int colIdx = table.columnAtPoint(e.getPoint());
            int rowIdx = table.rowAtPoint(e.getPoint());
Object obj = table.getModel().getValueAt(rowIdx, colIdx) ;//This gets the value in the cells
           String str = obj.toString();//This converts that Value to String
           JTextField somefield = new JTextField();//Choose a JTextField
           somefield.setText(str);//Populates the Clicked value to the JTextField

            System.out.println("Row: " + rowIdx + " " + "Colulmn: " + colIdx);
        }
        else if (header.equals(e.getSource())) {

            int selectedColumnIdx = header.columnAtPoint(e.getPoint());
            String colName = table.getColumnName(header.columnAtPoint(e.getPoint()));

            System.out.println("Column Name: " + colName);
            System.out.println("Selected Column: " + selectedColumnIdx);
        }
    }
}