2012-04-03 23 views
4

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

这里是我的表My table image

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

+0

另请参阅此[问与答](http://stackoverflow.com/q/7137786/230513)。 – trashgod 2012-04-03 14:11:19

回答

14

完全参见下面的工作

  • 例如添加一个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); 
    } 
}); 
+1

+1这是本教程中建议的方法,并在[此处](http://stackoverflow.com/a/7137801/230513)中进行了说明。 – trashgod 2012-08-02 18:42:26

+0

太棒了!我从来没有意识到鼠标点击头部的事件比桌面上的事件要好。:D – gumuruh 2017-10-09 16:31:13

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

修复示例代码以满足您的口味和偏好;

+0

最好使用['ListSelectionListener'](http://docs.oracle.com/javase/tutorial/uiswing/components/table。 html#selection)放在表格本身上。标题监听器重复@亚当的更早[回复](http://stackoverflow.com/a/9992631/230513)。 – trashgod 2012-08-02 10:46:34