是否可以在ActionListener
列标题中添加JTable
.
这是我的桌子
现在,我想ActionListener
在列标题中添加一个(例如WQE
,SDM
),我希望能够在另一个窗口中显示列描述。
是否可以在ActionListener
列标题中添加JTable
.
这是我的桌子
现在,我想ActionListener
在列标题中添加一个(例如WQE
,SDM
),我希望能够在另一个窗口中显示列描述。
请参阅下面的完整工作示例
代码:
// 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);
}
});
对的,这是可能的。您可以在列标题和单元格上添加鼠标事件,如下所示:
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);
}
}
}
修复示例代码以适合您的口味和偏好;