Determine Which JTable Cell is Clicked

2020-08-09 06:39发布

问题:

When a user clicks a cell on a JTable, how do I figure out the row and column of the clicked cell? How would I show this information in a JLabel?

回答1:

The existing answer works, but there is an alternate method that may work better if you're not enabling cell selection. Inside your MouseListener, do something like this:

public void mouseClicked(java.awt.event.MouseEvent event) {
    int row = theTable.rowAtPoint(event.getPoint());
    int col = theTable.columnAtPoint(event.getPoint());
    // ...


回答2:

You can use following methods on JTable to retrieve row and column of the selected cell:

int rowIndex = table.getSelectedRow();
int colIndex = table.getSelectedColumn();

And add a SelectionListener to table to catch the event when the table is selected.



回答3:

It is working for me!!!

jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
 public void mouseClicked(java.awt.event.MouseEvent evt) {
    int row = jTable1.rowAtPoint(evt.getPoint());
    int col = jTable1.columnAtPoint(evt.getPoint());
    if (row >= 0 && col >= 0) {


    }
 }
});


回答4:

did you try addMouseListener()? I hope you are about using Swing's JTable.



回答5:

I've found that when columns are hidden/reordered columnAtPoint returns the visible column index, which isn't what I needed. Code which worked for me is

int row = theTable.convertRowIndexToModel(theTable.rowAtPoint(event.getPoint()));
int col = theTable.convertColumnIndexToModel(theTable.columnAtPoint(event.getPoint()));