是否可以将ActionListener
添加到JTable
的列标题中。
这是我的表
现在,我想在列标题中添加ActionListener
(例如WQE
,SDM
)我希望能够在另一个窗口中显示列描述。
答案 0 :(得分:16)
请参阅下面的完整工作示例
代码:
// 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)
是的,这是可能的。您可以在Column标题和单元格上添加Mouse Event Both,如下所示:
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);
}
}
}
修复示例代码以适合您的品味和偏好;