简体   繁体   中英

Determine Which JTable Cell is Clicked

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 ?

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());
    // ...

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.

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) {


    }
 }
});

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM