简体   繁体   中英

How to add a type of listener to a JTable (Java)?

I have a column with plain text in it.

If the user double-clicks a row in that column, the column allows itself to be edited for that row (as it should).

I need something to detect when that text is done with being edited (when the user hits the enter key, for example). When that happens, I need something to get the row ID of that change (0-based of course).

Any ideas?

Thanks!

You should add a listener to the TableModel:

table.getModel().addTableModelListener(new TableModelListener() {

      public void tableChanged(TableModelEvent e) {
         // your code goes here;
      }
    });

TableModelEvent contains row and column number and type of modification.

I think the easiest way to get the location of the click in terms of row and column would be this:

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

        }
    }
});

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