2012-04-03 62 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