5

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

这是我的桌子我的桌子图片

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

4

2 回答 2

18

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

  • 将 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);
    }
});
于 2012-04-03T11:49:15.710 回答
1

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

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

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

于 2012-08-02T05:09:23.740 回答